JQuery-1.9.1 source code analysis series (16) ajax-response data processing and api sorting, jquery-1.9.1ajax

Source: Internet
Author: User
Tags text to json

JQuery-1.9.1 source code analysis series (16) ajax-response data processing and api sorting, jquery-1.9.1ajax

After ajax receives a request response, it mainly performs two processes: obtaining the response data and converting the data using the type converter.

A. Get Response Data

The ajaxHandleResponses function is called to obtain response data.

The functions of ajaxHandleResponses include:

-Set all responseXXX fields for jqXHR (the value is the response data)

-Find the correct ype (one of the content-type and the expected dataType)

-Return correct response data

Let's look at a response data format:

  responses = {    text: "{"code":500,"data":null,"message":"all exist","sessionId":"wsdfhl333sdfs"}"
  }

 

ResponseXXX has only two types of responseXML and responseText.

// Fill in the responseXXX (responseXML / responseText) field,
     for (type in responseFields) {
         if (type in responses) {
             jqXHR [responseFields [type]] = responses [type];
         }
     }

Find the correct ype. This is a process of one-by-one detection.

// Remove the automatically added dataType type and get the Content-Type type in the process
    while (dataTypes [0] === "*") {
        dataTypes.shift ();
        if (ct === undefined) {
            ct = s.mimeType || jqXHR.getResponseHeader ("Content-Type");
        }
    }

    // Check if we are dealing with a known content-type
    if (ct) {
        for (type in contents) {
            if (contents [type] && contents [type] .test (ct)) {
                dataTypes.unshift (type);
                break;
            }
        }
    }

    // Check to see if we have the expected data type response
    if (dataTypes [0] in responses) {
        finalDataType = dataTypes [0];
    } else {
        // Try a convertible data type
        for (type in responses) {
            if (! dataTypes [0] || s.converters [type + "" + dataTypes [0]]) {
                finalDataType = type;
                break;
            }
            if (! firstDataType) {
                firstDataType = type;
            }
        }
        // Or just use first one
        finalDataType = finalDataType || firstDataType;
    }

Return correct response data

// if we find a dataType
     // put dataType into dataTypes, if needed
     // return the corresponding response data
     if (finalDataType) {
         if (finalDataType! == dataTypes [0]) {
             dataTypes.unshift (finalDataType);
         }
Return responses [finalDataType];
}
} 

 

B. Type Converter

There are four types of ajax Converters

converters: {
            // convert anything to a string
            // window.String will be compressed into a.String in min file
            "* text": window.String,
 
            // The text is converted to HTML (true means no conversion is required, return directly)
            "text html": true,
 
            // convert text to JSON object
            "text json": jQuery.parseJSON,
 
            // convert text to XML
            "text xml": jQuery.parseXML
        }

Click jQuery. parseJSON/jQuery. parseXML to view details.

In addition, it has been specially developed for scripts.

// Ajax request sets the default value
jQuery.ajaxSetup ({
     / **
      * Content-Type sends a request header (Content-Type), which is used to notify the server of what type of return result 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);
             return text;
         }
}

Another one added during jsonp preprocessing

s.converters ["script json"] = function () {
                 if (! responseContainer) {
                     jQuery.error (callbackName + "was not called");
                 }
                 return responseContainer [0];
             };

 

DataType is nothing more than that

1: dataType is empty and automatically converted

At this time, jQuery can only guess the type to be processed based on the packet header information (in ajaxHandleResponses)

// Delete the wild dataType and get the returned Content-Type
while (dataTypes [0] === "*") {
     dataTypes.shift ();
     if (ct === undefined) {
         ct = s.mimeType || jqXHR.getResponseHeader ("Content-Type");
     }
}

Use xhr. getAllResponseHeaders () to obtain the packet header information, and then match the values of all Content-Type objects.

Of course, find this Content-Type = "html" and we have to check whether there is any corresponding processing method. If so, replace this PES ypes (in ajaxHandleResponses)

// see if we can handle Content-Type, binary types like this are not easy to handle
if (ct) {
     // in fact, it can handle text, xml and json
     for (type in contents) {
         if (contents [type] && contents [type] .test (ct)) {
             dataTypes.unshift (type);
             break;
         }
     }
}

After this process, dataTypes is changed to the corresponding html, which is an automatic conversion process in jquery.

 

2: specified by the dataType developer

Xml, json, script, html, jsop


After ajax is successful, the ajaxConvert function will be called for processing. To sum up, the converter converts the responseText or responseXML returned by the server to the Data Type ype specified during the request, if no Type is specified, the response header Content-Type is used for automatic processing. Select the response Converter Based on the target type to convert it to the target data.


C. JQuery. ajaxSetup (target [, settings])

If the function is used externally, the parameter settings is not used:SetAJAXGlobal default settings.

This function has two usage methods:

1. When the target and settings parameters are passed, create a complete and mature setting object (including ajaxSettings and the settings passed) and write it to the target. In the end, the global variable jQuery. ajaxSettings remains unchanged. This is mainly used internally by jQuery. External Use is meaningless.

2. When the settings does not exist (that is, there is only one parameter), the target is written to jQuery. ajaxSettings. This method is used externally. It mainly sets the global default settings of AJAX.

View Source Code

// Create a complete and mature settings object (including ajaxSettings and passed settings) to write to the target.
// If settings is omitted, write target to ajaxSettings.
ajaxSetup: function (target, settings) {
     return settings?
         ajaxExtend (ajaxExtend (target, jQuery.ajaxSettings), settings):
         ajaxExtend (jQuery.ajaxSettings, target);
}

Use the ajaxExtend function, specify those options through jQuery. ajaxSettings. flatOptions without in-depth expansion (deep copy replacement), and perform other in-depth expansion. By default, there are only two options without in-depth expansion: jQuery. ajaxSettings. flatOptions: {url: true, context: true }. You can add options that do not require in-depth expansion to jQuery. ajaxSettings. flatOptions.

// Specially extended functions for ajax options
// For options in flatOptions (no need for deep expansion (deep copy replacement))
function ajaxExtend (target, src) {
     var deep, key,
         flatOptions = jQuery.ajaxSettings.flatOptions || {};

     // Options that do not require deep expansion are stored in target [key], and options that require deep expansion are stored in deep [key].
     for (key in src) {
         if (src [key]! == undefined) {
             (flatOptions [key]? target: (deep || (deep = (}))) [key] = src [key];
         }
     }
     // Extend the content in deep (deep copy replacement) to target
     if (deep) {
         jQuery.extend (true, target, deep);
     }
     return target;
} 

 

D. ajax related APIs

JQuery. get (url [, data] [, success] [, type])(Function usedPassHTTP GETFormatAJAXRequest to obtain remote data.

The jQuery. get () function is used to implement simple AJAX requests in the form of GET.JQuery. ajax ()To achieve this, but omitted most of the parameter settings that are not commonly used, and limited to the http get method. Note that this function isAsynchronousMethod To load data. JQuery. get () isGlobal Method(You can call it without creating a jQuery object. You can understand it as a static function ). JQuery also hasInstance methodGet ()Used to obtain the DOM elements of the specified index matched in the current jQuery object .)

 

JQuery. post (url [, data] [, success] [, type])(Function usedPassHTTP POSTFormatAJAXRequest to obtain remote data.

The jQuery. post () function is used to implement simple POST-form Ajax requests.JQuery. ajax ()To achieve this, but omitted most of the parameter settings that are not commonly used, and limited to the http post method. Note that this function isAsynchronousMethod To load data)

 

JQuery. getJSON (url [, data] [, success])(Function usedPassHTTP GETFormatAJAXRequest Remote RetrievalJSONEncoded data.JSON is a data format. JS native supports JSON format. jQuery first tries to convert the JSON data obtained from the server through jQuery. getJSON () to the corresponding JS object. If the request URL contains"CallBack =? "JQuery will automatically regard it as JSONP and execute the corresponding callback function to obtain JSON data.

Important: JSON data returned by the server must complyStrictJSON syntax. For example, all attribute names must be addedDouble quotation marks, All string values must also be addedDouble quotation marks(Not single quotes ). Note that this function isAsynchronous.)

 

JQuery. getScript (url [, success])(Function usedPassHTTP GETForm LoadingJavaScriptFile and run it.This function is used to dynamically load the JS file and execute the JS Code in the file under the global scope. This function can load cross-origin JS files. Note that this function isAsynchronousMethod To load data)

 

JQuery. fn. load (url [, data] [, complete])(Function usedLoad data from the server and use the returnedHtmlContent replaces the content of the currently matched element.Load ()The function uses the GET method by default.ObjectThe data is automatically converted to the POST method.Load ()The function only replaces the internal content (innerHTML) of each matching element.DataTypeIsHtml. You can append the specified selector to the end of the URL string (separated by spaces) to facilitate the use of only the loaded html documentMatching SelectorTo replace the content of the currently matched element. If this document does not match the content of the selector, use a null string ("") to replace the content of the currently matched element.

If the current jQuery objectNoIf any element is matched, no Remote Load request is executed.

Here we will introduceLoad ()Is an Ajax request function. jQuery also has an event function with the same name.Load ()Used to execute the specified function when the file is loaded. This function belongsJQueryObject (instance ). The function is based on the function at the underlying layer.JQuery. ajax ()Implemented)

 

JQuery. ajaxPrefilter ([dataType,] handler)(Function usedPre-processingAjaxThe callback function of the Parameter options.When all Parameter options areJQuery. ajax ()Before function processing, you can use the callback function set by this function to modify any Parameter options in advance.

You can also specify the data type (dataType) to process only the Parameter options of the specified data type in advance. This function can be called multiple times to specify different callback functions for AJAX requests of different data types.

DataType (optional/String type)

A string consisting of one or more data types separated by spaces. If this parameter is not specified, it indicates all data types. Available data types include xml, html, text, json, jsonp, and script ". This string is any combination between them (multiple types are separated by spaces), such as "xml", "text html", and "script json jsonp ".

Handler (Function type)

The callback function used for preprocessing Parameter options. It has the following three parameters:

Options(Object) All Parameter options of the current AJAX request.

OriginalOptions(Object) passed to $.Ajax() Unmodified Parameter options of the method.

JqXHR: Current requestedJqXHRObject(XMLHttpRequest object encapsulated by jQuery ).

)

 

JQuery. ajaxSetup (settingsObj )(Function usedSetAJAXGlobal default settings.This function is used to change the default setting options of AJAX requests in jQuery. For all AJAX requests executed later, if the corresponding option parameter is not set, the changed default settings will be used .)

 

JQuery. fn. serialize ()(The function is usedSerialize a set of form elements and encode the form content as a string for submission.Serialize ()FunctionIt is often used to serialize form content for AJAX submission.

This function is mainly based onUsed for submissionOfValidName and value of the Form Control.SplicingIs a text string that can be directly used for form submission that has been processed by standard URL encoding (character set encoding is UTF-8 ).

This functionNoSerializationYou do not need to submitForm Control, which is consistent with the regular form submission behavior. For example: form controls that are not in the <form> label are not submitted, form controls without the name attribute are not submitted, form controls with the disabled attribute are not submitted, and unselected form controls are not submitted.

And regular form submissionDifferentNormally, the button control with name is submitted.Serialize ()The function does not serialize the button control with name .)

 

JQuery. fn. serializeArray ()(The function is usedSerialize a set of form elements and encode the form content intoJavaScriptArray.It is often used to serialize form content into a JSON object, so that it can be encoded as a JSON string.

This function willCan be used for submissionEach form control of is encapsulated into an Object. The Object has the name and value Attributes and corresponds to the name and value attributes of the Form Control. Then, these Object objects are encapsulated into an array and returned.

This function will not be serializedYou do not need to submitForm Control, which is consistent with the regular form submission behavior. For example: form controls that are not in the <form> label are not submitted, form controls without the name attribute are not submitted, form controls with the disabled attribute are not submitted, and unselected form controls are not submitted.

And regular form submissionDifferentNormally, the button control with name is submitted.SerializeArray ()The function does not serialize the button control with name .)

 

JQuery. param (obj [, traditional])(SetJSArrays or pure objects are serialized as string values for use inURLQuery string orAJAXRequest.If the input is not an array or "Pure object", an empty string ("") is returned. If the input isNull,UndefinedIf you cannot access the attribute value, an error is reported.

The so-called "Pure object" means{}OrNew Object ()A self-created object. JS built-in Boolean, Number, String, Date, RegExp, Function, Window and other types of objects are not considered as "Pure objects ".

The returned string has been URL encoded (using the character set as the UTF-8 ))

 

JQuery. fn. ajaxStart (handlerFn)(AJAXRequestedAjaxStartEvent binding handler)

JQuery. fn. ajaxSend (handlerFn)(WhenAJAXThe callback function executed when the request is about to be sent .)

JQuery. fn. ajaxComplete (handlerFn)(WhenAJAXRequest completed(Whether successful or failed).)

JQuery. fn. ajaxSuccess (handlerFn)(WhenAJAXThe callback function executed when the request is successfully completed .)

JQuery. fn. ajaxError (handlerFn)(WhenAJAXThe callback function executed when the request fails .)

JQuery. fn. ajaxStop (handlerFn)(AJAXRequestedAjaxStopEvent binding handler .)


So far, the source code of jQuery 1.9.1 has been analyzed. You are welcome to make corrections.

 

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.