JQuery-1.9.1 source code analysis series (16) ajax -- jsonp principle, jquery-1.9.1jsonp

Source: Internet
Author: User

JQuery-1.9.1 source code analysis series (16) ajax -- jsonp principle, jquery-1.9.1jsonp

Json jsonpType

"Json": The response result is executed as JSON and a JavaScript Object is returned. If you specifyjsonThe response result is used as an object before being passed to a successful processing function.JQuery. parseJSON. The parsed JSON object can bejqXHRObjectresponseJSONProperty. As long as the result is converted to the json format in the ajaxConvert method, this is the subsequent content. Here we mainly study jsonp preprocessing.

"Jsonp":JSONPIs an unofficial protocol that allows the server to integrate Script tags to return to the client and implement cross-origin access through javascript callback (this is only a simple implementation form of JSONP ).

Cross-OriginThe root cause of this problem is the browser's same-origin policy restriction. Understanding the same-origin policy restriction the same-origin policy is to prevent code from obtaining or modifying files or information obtained from another domain name. That is to say, our request address must be the same as that of the current website. The same-origin policy protects resources by isolation. This strategy has a long history since the Netscape Navigator 2.0 era.

A relatively simple solution to this limitation is to send requests on the server side, and the server acts as a proxy relay to reach third-party resources. Although widely used, this method is not flexible enough.

Another method is to use the framework (frames) to include resources of third-party sites, but the resources included are also subject to the same-source policy restrictions.

One clever way is to use dynamic code elements on the page. The source of the code points to the service address and loads data in your own code. When the code is loaded and executed, the same-source policy will not limit the execution. However, if the Code fails to download an Object, we can use JSON (JavaScript Object Notation) to improve this application.

  

A. JSONP Client implementation

  Let's take a look at a simple example.

<!DOCTYPE html>

Using scripts as src to load remote jQuery is undoubtedly normal, so it is not difficult to find that the js file is not affected by cross-origin when it is called on the web page.

Of course, we also find that all tags with the "src" attribute have cross-domain capabilities, such as <script>, , and <iframe>.

 

  In the future, we replace it with a contractual interface.

<! DOCTYPE html> RemoteLoad(Data) {alert (data) // Remote data} </script> After ready)RemoteLoad('Loaded data ')

Obviously, it is feasible to load a remote script and execute it locally, which bypasses the cross-origin issue, but such a request is problematic. Is the interface contractual?

How can remote js know the name of the local function that should be called? After all, jsonp service providers have to deal with many service objects, and these service objects have different local functions? Let's look down.

 

  Further increase of dynamic callback

<!DOCTYPE html> remoteLoad= function(data){};    var url = "http://code.jquery.com/jquery-1.11.1.min.js?code=1111&callback=remoteLoad";    var script = document.createElement('script');    script.setAttribute('src', url);    document.getElementsByTagName('head')[0].appendChild(script); </script>

Instead of Directly Writing remote js files to death, the code is used for dynamic query, which is also the core part of the jsonp client implementation, we can see that a callback parameter is passed in the called url to tell the server that my local callback function is called remoteLoad. Therefore, please pass the query result to this function for calling.

 

B. JQuery Processing

  In jQuery ajax, jsonp and jsonpCallback specify the "callback" and "remoteLoad" values respectively.

The default value of jsonp is "callback", and the default value of jsonpCallback is a timestamp field (jQuery. expando + "_" + (ajax_nonce ++), for example, "jquery19107833043907303363_144 ".

We can also specify them, such as {jsonp: "chuaCallBack", jsonpCallBack: "chuaRemote"}, then the url becomes "http://code.jquery.com/jquery-1.11.1.min.js ?.. &ChuaCallBack=ChuaRemote".

To sum up, a core point of json is that users are allowed to pass a callback parameter to the server. When the server returns data, the callback parameter is used as the function name to enclose JSON data, in this way, the client can customize its own functions to automatically process the returned data.

$. Ajax ({url: "remoteLoad. js ", dataType:" jsonp ", jsonp:" callback ", // The parameter name that is passed to the request handler or page to obtain the jsonp callback function name (generally the default value is: callback) jsonpCallback: "Handler", // The Custom jsonp callback function name. The default value is the random function name automatically generated by jQuery. You can also enter "? ", JQuery automatically processes data for you. success: function (data) {console. log (arguments )}});

  Basic PrinciplesOKNow, let's look at the aboveJQueryThere is no big difference in the use.

JQuery is also similar,JQueryThe biggest difference is that the callback function is automatically generated for you and the data is retrieved.SuccessProperty method to call,It is not a passed callback handle.

The following describes how to process jsonp source code using jQuery.

First,We needSet the callback function name,You can define it yourself or makeJQuerySet automatically.

// Obtain the callback function name (this name can be set on the jsonpCallback option of ajax, // otherwise it can be set through jsonpCallback () by jQuery by default) // The callback function name is used to tell the background to wrap the returned data to the function. After returning the result, run callbackName = s. jsonpCallback = jQuery. isFunction (s. jsonpCallback )? S. jsonpCallback (): s. jsonpCallback;

Then,Insert callbackUrlOrDataOption (in generalURL)

if ( jsonProp ) {    s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );} else if ( s.jsonp !== false ) {    s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;}

Then, install the callback

// Install callbackOverwritten= Window [callbackName]; window [callbackName] = function () {responseContainer = arguments ;};

Obviously, the background should have executed the overwritten callback, but now it is replaced by the rewrite callback after the execution. Do not rush to overwritten for later use.

Finally, add the always response of the delayed object to execute overwritten.

// Clear the function (executed after conversion) jqXHR. always (function () {// Save the previously stored value window [callbackName] = overwritten; // set jsonpCallback back to the original value if (s [callbackName]) {// make sure that the jsonpCallback option is reused without any impurity s. jsonpCallback = originalSettings. jsonpCallback; // press callbackName into oldCallbacks for future use of oldCallbacks. push (callbackName);} // after the request is responded, if the callback specified by jsonpCallback is a function, call it if (responseContainer & jQuery. isFunction (overwritten )){Overwritten (responseContainer [0]);} ResponseContainer = overwritten = undefined ;});

Therefore, overwritten is executed here. The previously overloaded callback in the source code gets the responseContainer value after being called in the background. The callback corresponding to the callback name (such as chuaRemote) specified in the jsonpCallback option is saved to overwritten first, and the original chuaRemote is assigned function () {responseContainer = arguments ;};

In Response Processing, chuaRemote is called to obtain the response value from responseContainer. Finally, the added function is executed in jqXHR. always. Restore chuaRemote to the original function overwritten and execute overwritten (callback specified by jsonpCallback ). The main reason is that the always listener also clears the function specified by callbackName and adds the function back to history.

  

Now let's analyze jsonp. You are welcome to make a brick.

 

If you think this article is good, click [recommendation] in the lower right corner ]!

 

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.