Comprehensive Analysis of Ajax and jsonp usage summary, comprehensive analysis of ajaxjsonp

Source: Internet
Author: User
Tags getscript

Comprehensive Analysis of Ajax and jsonp usage summary, comprehensive analysis of ajaxjsonp

Ajax and jsonp can communicate with the background to obtain data and information, but do not need to refresh the entire page to partially refresh the page.

I. ajax

• Definition: a technology that sends an http request and implements asynchronous communication with the background.

• Principle: instantiate an xmlhttp object to communicate with the background.

Ajax same-origin policy:

• The pages or resources requested by ajax can only be resources under the same domain, not those in other domains. This is based on security considerations when designing ajax.

--------------------------------------------------------------------------------

Ajax method:

1. $. ajax ({}):

• Common parameters: • url: Request network address
• Type: Request method. The default value is 'get'. 'post' is commonly used'
• DataType: sets the returned data format, which is json or html or jsonp;
• Data: Set the data sent to the server
•. Done (): Set the callback function after the request is successful.
•. Fail (): Set the callback function after the request fails.
• Async: sets whether asynchronous. The default value is 'true', indicating asynchronous

• Code application:

$ (Function () {$ ("input "). click (function () {$. ajax ({url :". /data. json ", type:" get ", dataType:" json ",});. done (function (data) {// callback function for successful request $ ("input "). val (dat. name );}). fail (function () {alert ('server timed out. Please try again! ');});});})...... <Body> <div> <input type = "button" value = "xinzhi"> </div> </body>

Description: data indicates the data returned by the background. ajax is dependent on the server environment.

2. $. get ():

• The $. get () method uses GET requests to load data from the server. It is also an ajax Method for refreshing request data.

• Parameters:
• Url: the url to be accessed. The same-origin policy must be followed;
• Data: the data sent to the server.
• Function (data, status) {}: function that successfully runs the request
• DataType: Data Type of the request response.

// Reference code: $ (function () {$ ("input "). click (function () {$. get (". /data. json ", function (data, status) {console. log (data. name) ;}, "json ");});})...... <body> <div> <input type = "button" value = "xinzhi"> </div> </body>

• The parameters of the $. get () method are different from those of the $. ajax () method. The url is a required parameter, and the other three are optional.
• Data is the returned data, and status indicates the Request status, which generally includes "" success "," error ", and" timeout.
• If the datatype type is jsonp, you can also request data across domains.
• No callback function for request failure.

3. $. post ()

• The $. get () method uses the POST request to load data from the server;
• The method used is exactly the same as the $. get () method.

4. $. load ():

• Load data from the server without specifying datatype. The returned data is automatically placed in the element.
• Parameters:

• URL: address;
• Data: The request parameter. Optional;
• Function (response, status, xhr): callback function for successful requests.

$(function () {  $("input").click(function () {    $(".box").load(      "./data.json",      function (response,status) {        console.log(data.name);      }    );  });})......<body>  <div>    <input type="button" value="xinzhi">    <div class="box"></div>  </div></body>

• The returned data is placed in the div;
• Data cannot be accessed across domains;
• Response indicates the returned data, and status indicates the Request status;
• No callback function for request failure.

4. getJSON ()

• Obtain JSON Data Using ajax http get requests.
• Parameters:
• Url: Required parameter for the request url;
• Data: the data sent to the server;
• Function (data, status, xhr): callback function for successful requests

$(function () {  $("input").click(function () {    $.getJSON(      "./data.json",      function(data,status) {        console.log(data.name);      },    );  });})......<body>  <div>    <input type="button" value="xinzhi">  </div></body>

• The method directly obtains json data;

• No callback functions fail to be returned;

• Name a function during callback, not an anonymous function;

5. getScript ()

• Obtain and execute js code using the http get request of AJAX.

• Parameters:

• Url: Required parameter for the request url;

• Function (data, status): callback function for successful requests

$(function () {  $("input").click(function () {    $.getScript(      "./data.js",      function(data,status) {        console.log(data);      },    );  });})......<body>  <div>    <input type="button" value="xinzhi">  </div></body>

• Js Code is returned for data completion;

• This method can be used to dynamically load js Code.

Ii. jsonp

• Definition: a data communication format that enables cross-origin http request sending and can be embedded in ajax.
• Principle: Use script tags to link resources across domains.

Usage 1: function parameters

<script type="text/javascript">  function aa(data){    console.log(data.name);  }</script><script type="text/javascript" src="....../data.js"></script>

Description: defines a data. js file externally. The file path can be different from the current page in the same domain.

Data. js content:

aa({    "data":{    "name":"xiaohong",    "age":"18"  }})

• Pass data in the form of page-defined function parameters to obtain data.

• Data can be split in essence so that data does not need to be forcibly stored under the same domain name.

Usage 2: Use ajax

$. Ajax ({url :'..... /data. js', // It may not be a local domain name type: 'get', dataType: 'jsonp', // access jsonpCallback: 'A' in jsonp format }). done (function (data) {console. log (data. name );}). fail (function () {alert ('server timed out. Please try again! ');});

• Data. js has the same content as above.

• The ajax method is essentially a script tag that can link resources across domains, but jquery encapsulates the same method for it and looks the same.

• The Execution Process of the above Code is: ajax cross-origin access to data through jsonp technology. js file, and pass its parameters. run the data parameter of the done method. done method.

• At present, this method still has its limitations, that is, it must know the name and definition of the data. js file method aa. If you only know the domain name, you need another method.

Usage 3

Var $ input = $ ("input"); $ input. keyup (function () {$. ajax ({url: 'https: // sug.so.360.cn/suggest? ', // Request 360 for the Lenovo data type: 'get', dataType: 'jsonp', // access data in jsonp format: {word: $ input. val ()},}). done (function (data) {console. log (data );}). fail (function () {alert ('server timed out. Please try again! ') ;}) ...... <Body> <input type = "text"> </body>

• View the data packet sent back by the server each time the keyword is entered in the browser, find the header address in the js file and related submitted data, and find that the key is the word keyword, so you can send data to the server.
• The data returned by the server is automatically transmitted to the callback's anonymous function parameter data.

Summary

The above is a summary of Ajax and jsonp. For more information, see

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.