jquery Source Analysis Series (JSONP): Ajax-preprocessing

Source: Internet
Author: User

上一章大概讲了前置过滤器和请求分发器的作用,这一章主要是具体分析每种对应的处理方式

$.ajax()Calls to different types of responses are passed to a successful handler before being processed in different kinds of preprocessing (prefilters). The type of preprocessing depends on the content-type response, which is closer to the default, but can be set explicitly using dataType options. If an option is provided dataType , the Content-type header information for the response is ignored.

Valid data types are text, HTML, XML, JSON,JSONP, and script.

DataType: expected data type returned by the server. If not specified, JQuery is automatically judged intelligently based on the HTTP packet mime information, such as the XML MIME type being recognized as XML. In 1.4, JSON generates a JavaScript object, and script executes it. The data returned by the server is then parsed against this value and passed to the callback function. Available values:

Script type

$.ajax ({    type     "GET"    ,    url      "     test.js", "script", function (JQXHR, status) {        Console.log (jqxhr, status)    }});

According to the API's instructions, if the datatype type is script, you need to handle

1 Execute Script

2 content returned as plain text

3 By default, the result is not automatically cached by appending the query string variable "_=[timestamp]" in the URL unless the cache parameter is set totrue

4 on a remote request (not in the same domain), all post requests are converted to get requests. (because the script tag of the DOM will be used to load)

For the above four points, we look at the process of processing

Inspectprefiltersortransports (Prefilters, S, Options, JQXHR);

At this point the datatype type will pass through the corresponding preprocessing ajaxprefilter ("script")

Cache (Default: true, dataType为"script"和"jsonp"时默认为false )

function (s) {    if (s.cache = = = undefined        ) {false;    }     if (s.crossdomain) {        = "GET";    }});

The preprocessing process is to cache it to false and the browser will not cache this page

This appends a timestamp parameter to the query string of the requested URL to ensure that each browser-downloaded script is re-requested

It works by attaching "_={timestamp}" to the GET request parameter with a timestamp after the requested address

if false ) {    = rts.test (cacheurl)?    // If There is already a ' _ ' parameter and set its value    Cacheurl.replace (RTS, "$1_=" + ajax_nonce++):    //  Otherwise add one to the end    Cacheurl + (Ajax_rquery.test (cacheurl)? "&": "?") + "_=" + ajax_nonce++;}

At this time the S.url = "test.js?_=1402362401890";

This parameter is not required for other requests except in IE8 when a POST request has a URL that has been requested with get

JSON JSONP type

    • JSON: Executes the result of the response as JSON and returns a JavaScript object. In jquery 1.4, JSON-formatted data is parsed in a strict way, and if there is a malformed format, JQuery is rejected and throws an exception that parses the error. (See json.org For more information, the correct JSON format.) )
    • If specified, the json response result is used for parsing as an object before being passed to the success handler jQuery.parseJSON . The parsed JSON object can be obtained through the properties of the jqXHR object responseJSON .
    • JSON processing as long as the results in the Ajaxconvert method is converted to the need is JSON format, this is the later content, here is the main study of JSONP preprocessing

About JSONP Transfer aircraft: http://baike.baidu.com/view/2131174.htm

JSONP is an unofficial protocol that allows the server-side integration of script tags to return to the client, with the form of JavaScript callback for cross-domain access (this is just the JSONP simple implementation form). The development method of JSON system is a typical data structure-oriented analysis and design method, with activity as the center, a series of sequence of activities are combined into a complete working process.

cross-domain the root cause of this problem is the browser's same-Origin policy restrictions, the understanding of the same-origin policy restriction the same-origin policy is to prevent code from obtaining or changing files or information obtained from another domain name. This means that our request address must be the same as the current site. The same-origin policy enables protection of resources through isolation. The history of this strategy has been very long since the Netscape Navigator 2.0 era.

    • A relatively simple solution to this limitation is to send a request on the server side, which acts as a proxy relay to a third-party resource. Although it is widely used, but this method is not flexible enough.
    • Another option is to use the framework (frames) to include resources from third-party sites, but the resources included are also subject to the same-origin policy.
    • One clever way to do this is to use dynamic code elements in the page, where the source of the code points to the service address and loads the data in its own code. When these code loads execute, the same-origin policy does not limit. But if the code tries to download the file and it fails, fortunately, we can use JSON (JavaScript Object Notation) to improve the application

JSON and JSONP

JSON is a lightweight data interchange format compared to XML. The reason JSON is fascinating to JavaScript developers is that JSON itself is an object in JavaScript.

For example, a ticker object

var ticker = {symbol: ' IBM ', price:100}

And the JSON string is {symbol: ' IBM ', price:100}

This allows us to pass the JSON data in the parameters of the function. It's easy to master the use of dynamic JSON parameter data in functions, but that's not what we're aiming at.

By enabling our functions to load dynamic JSON data, we are able to handle dynamic data, a technique known as the dynamical Javascript insertion.

In index.html

function Showprice (data) {      alert ("Symbol:" + Data.symbol + ", Price:" + Data.price);  }

Then dynamically load the Ticker.js script

var data = {symbol: ' IBM ', price:100};  Showprice (data);

Code executes functions to load data by adding JavaScript code dynamically

As mentioned earlier, the same-origin policy does not apply to dynamically inserted code. That is, you can load code from different domains to execute JSON data in their code.

This is Jsonp (JSON with Padding). Note that when you use this method, you must define a callback function in the page, just like the showprice in the previous example.

What we typically call the JSONP service (remote JSON service) is actually an extended support for the ability to include return data in a user-defined function. This method relies on having to accept the name of a callback function as a parameter.

It then executes the function, processes the JSON data, and displays it on the customer's page.

JSONP Client-specific implementations:

<! DOCTYPE html>        alert (jquery)     </script>

By script is src loading remote jquery is no doubt that can run normally, so it is not difficult to find the Web page call JS file is not affected by whether cross-domain

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

In the further we switched to the contractual interface

<! DOCTYPE html>function  remoteload (data) {                // Remote Data         }    </script >http://code.jquery.com/ Execute remoteload (' Loaded data ') in Jquery-1.11.1.min.js file

Obviously OK, by loading the remote script to the local execution, well bypass the cross-domain problem, but such a request is problematic, the interface is contractual?

How to let the remote JS know what it should call the local function name? After all, JSONP service providers have to face a lot of service objects, and these service objects are different local functions? We went on to look down.

Further increase the dynamic callback

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">varRemoteload=function(data) {};       varurl = "Http://code.jquery.com/jquery-1.11.1.min.js?code=1111&callback=remoteLoad";             varScript = document.createelement (' script '); Script.setattribute (' SRC ', URL);document.getElementsByTagName (' head ') [0].appendchild (script); </script>

No longer directly to the remote JS file to write dead, but the code to implement dynamic query, and this is the core part of the JSONP client implementation, the focus of this example is how to complete the JSONP call the whole process.

We see the URL of the call passed a callback parameter tells the server, my local callback function is called Remoteload, so please pass the query results into this function to call.

So the summary is actually a core point of JSON: allow the user to pass a callback parameter to the server, and then the server returns the data when the callback parameter as the function name to wrap the JSON data, so that the client can arbitrarily customize their own functions to automatically process the return data.

The basic principle OK, we look at the implementation of jquery, in fact, it is similar

$.ajax ({    URL           "remoteload.js",    dataType      "Jsonp",    jsonp           the name of the parameter passed to the request handler or page to obtain the name of the JSONP callback function (typically default: callback)    // custom JSONP callback function names, The default is jquery automatically generated random function name, you can also write "?", jquery will automatically process data for you    {        Console.log ( arguments)    });

The difference between jquery and the most different will automatically help you to generate a callback function and extract the data for the success property method to invoke, not a callback handle passed

It's a long time. The next chapter merges the internal implementation and the request dispatcher


If you think this article is helpful to you, please click "Recommend", would you like to make progress with me? Then "pay attention" to me!

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.