jquery Source Analysis Series ($): Ajax-type converter

Source: Internet
Author: User
Tags text to json

What is a type converter?

jquery supports data return forms in different formats, such as datatype for XML, json,jsonp,script, or HTML

But the browser's XMLHttpRequest object responds to the data only ResponseText and responsexml two kinds

So now I'm going to define datatype as Jsonp, so the final data is a JSON key-value pair, so jquery's internal will help you do the conversion work by default.

jquery introduces a type converter to handle the conversion of this post-execution data, and automatically processes it based on the response header Content-type if no type is specified

Data transfer, the server can only return a string form, so if we datatype as JSOP or JSON

The data returned by the server is

ResponseText: "{" A ": 1," B ": 2," C ": 3," D ": 4," E ": 5}"
To transform into
Responsejson:object    {        1        23        4 5             }        

The transport of the server can only return data of type string, but if the user defines the JSON format through jquery's datatype, the data will be converted to object by default.

That's what we do with jquery's internal intelligence.

In jquery, the custom datatype is mapped to the data returned by the server, and the corresponding processing handle is stored through converters.

Put the required type converter Ajaxconvert on the server side after the response succeeds, the pair is defined in jquery. The converters in Ajaxsettings is traversed to find the conversion function that matches the data type and executes.

Mapping of Converters:

Converters: {//Convert Anything to text,           //convert any content to a string           //window. String will be compressed to a.string in min file"* Text": Window. String,//Text to HTML (true = no transformation)           //text converted to HTML (true means no conversion required, return directly)"Text HTML":true,            //Evaluate text as a JSON expression           //convert text to JSON"Text JSON": Jquery.parsejson,//Parse text as XML           //convert text to XML"Text xml": Jquery.parsexml}

In addition to the additional extensions part of the JSONP processing

//AJAX requests to set default valuesJquery.ajaxsetup ({/** * Content type sends the request header (Content-type), which informs the server what type of return results the request needs to receive.     * If the accepts setting needs to be modified, it is recommended to set it once in the $.ajaxsetup () method. * @type {Object}*/accepts: {script:"Text/javascript, Application/javascript, Application/ecmascript, Application/x-ecmascript"}, Contents: {script:/(?: JAVA|ECMA) script/    },Converters: {"Text Script":function(text) {jquery.globaleval (text); returntext; }    }});

So the format is

Text–> (Html,json,script) was disposed of

The implication is that the server returns a text format for just string type, which needs to be translated into the datatype type of data the user wants.

{"* text": window. String, "text html": True, "text json": Jquery.parsejson, "text xml": Jquery.parsexml}

The type of conversion occurs after the server returns data, so the corresponding is done in the Ajax method, of course, the finished method has been wrapped by the request dispatcher, as to why the above chapter has been mentioned, in order to deal with the normal request and JSONP cross-domain request problem

So when the AJAX request is complete, it calls the closure function done, which in doing determines whether the request succeeds, and if it succeeds, invokes Ajaxconvert to convert the data in response to the type

So before you do this:

1: Correctly assign the datatype type if the user does not set (empty) the situation

2: Need to convert to Converters mapping table corresponding to the format such as (* text, text HTML, text XML, text JSON)

Conversion of datatype types

The parameters of the datatype type, which can be XML, JSON, script, or HTML, or simply empty, then jquery needs a way to determine what data is currently being processed

Therefore, the introduction of

Ajaxhandleresponses processing the response converter to resolve the correct datatype type
Response = Ajaxhandleresponses (s, jqxhr, responses);

DataType can't do that in just a few cases.

1:datatype is empty, automatic conversion

At this point jquery can only guess based on the type of header information currently needed to be processed

// Remove the PASS datatype and get the returned Content-type  while (Datatypes[0] = = = "*") {    datatypes.shift (    ); if (ct = = = undefined        ) {= S.mimetype | | jqxhr.getresponseheader ("content-type");}    }

Get header information through Xhr.getallresponseheaders () and then go to match the values of all Content-type objects

Of course Find this content-type = "html", we also have to see if there is a corresponding processing method, if there is a need to replace this datatypes

// See if we can deal with the content-type, the binary type of this kind of chip is not good to deal with if (CT) {    //  can actually handle text, XML, and JSON for in      contents) {         if (Contents[type] && contents[type].test (CT)) {            datatypes.unshift (type);              Break ;        }    }}

After this process, datatypes would have been * became the corresponding HTML, this is jquery internal automatic conversion process

2:datatype Developer Designation

XML, JSON, script, HTML, JSOP

Summarize:

The type converter converts the ResponseText or responsexml of the service-side response to the data type specified at the time of the request datatype,

Automatic processing according to the response header Content-type if no type is specified

The execution process of a type converter
Response = Ajaxconvert (s, Response, JQXHR, issuccess);

SOURCE section

functionAjaxconvert (S, Response, JQXHR, issuccess) { current=Datatypes.shift ();  while(current) {if(current) {//If you encounter an * number, which is an arbitrary type, and it is not meaningful to convert to any type *            if(current = = = "*") { current=prev; //the focus of transformation                //if it is not an arbitrary type, and a different type is found}Else if(Prev!== "*" && prev!==Current ) {                //Seek a direct converter                //composition mapping format, matching converter                //* Text:function String () {[native code]}                //Script json:function () {                //text Html:true                //text Json:function Parse () {[native code]}                //text script:function (text) {                //text xml:function (data) {CONV = converters[prev + "+ Current" | | converters["*" +Current ]; //If None found, seek a pair                //If the converter is not found                //Does the Jsonp have browser execution, or do you want to call Globaleval                if(!Conv) {                    //...............                }                //Apply Converter (if not an equivalence)                //if there is a corresponding processing handle, perform the conversion                if(CONV!==true) {                    //unless errors is allowed to bubble, catch and return them                    if(CONV && s["throws"]) {response=Conv (response); } Else {                        Try {                            //executes the corresponding processing handle to the data returned by the incoming serverResponse =Conv (response); } Catch(e) {return{state:"ParserError", Error:conv? E: "No conversion from" + prev + "to" +Current }; }                    }                }            }        }    }    return{state:"Success", data:response};}

Process

1. Traverse the corresponding processing rule "script", "JSON" in datatypes

2. Making the return data interface for the JQXHR object

    1. JSON: "Responsejson"
    2. Text: "ResponseText"
    3. XML: "Responsexml"

such as: Jqxhr.responsetext: "{" A ": 1," B ": 2," C ": 3," D ": 4," E ": 5}"

3. Generate matching rules for the converter to find the right processor

4. Return the processed data response

Analyze the special JSONP conversion process

First look at the conversion processor

Jsonp

function () {            if (!  Responsecontainer) {                + "is not called");            }             return responsecontainer[0];};

The JSONP converter simply takes the corresponding value out of the Responsecontainer, so responsecontainer must convert the data to an array of objects after the conversion.

Of course do source analysis need a bit of their own guess ability, such as

Responsecontainer How does this array object come into being?

So we know the principle of jsonp, or by loading script, and then the server returns a callback function, Responsecontainer data is the argument of the callback function

So we need to satisfy the responsecontainer, we must first load the script first, so we have to go to the Distributor to find the corresponding loading code

First, the responsecontainer is an internal variable, with only one source, adding a global temporary function at the time of preprocessing

Then the code must have executed this function in order to assign the arguments parameter to Responsecontainer

overwritten =function() {    = arguments;};

Callbcakname is a log name created internally

function () {    = arguments;};

We send a request

Http://192.168.1.114/yii/demos/test.php?backfunc=jQuery203029543792246840894_1403062512436&action=aaron &_=1403062601515

After the server over the callback, executed the jquery203029543792246840894_1403062512436 (Responsecontainer);

So the global callbackname function needs to be loaded in the dispatcher before it can be executed to intercept the data returned by the server.

I can not each analysis in place, so we have the choice of their own according to the needs to see the source bar, the general flow of ideas to understand, it looks very soon, as for the remaining types, after the encounter will be in the analysis of the

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.