JQuery ajax response data processing

Source: Internet
Author: User
Tags character set extend http post instance method json object object text to json javascript array

Ajax will do two processing after getting a request response: Get response data and convert data using type converters

A. Getting response data

Get response data is called ajaxhandleresponses function to handle.

The functions of ajaxhandleresponses are:

-Set all responsexxx fields for JQXHR (value is response data)

-Find the right datatype (one of both Content-type and expected datatype)

-Returns the correct response data

Let's look at a format for response data:

Responses = {
Text: "{" Code ": $," data ": null," message ":" All Exist "," sessionId ":" Wsdfhl333sdfs "}"
}



There are only two kinds of responsexml and ResponseText set responsexxx

Fill in the Responsexxx (responsexml/responsetext) field,
For (type in responsefields) {
If (type in responses) {
jqxhr[Responsefields[type]] = responses[type];
}
}

Find the right datatype. This is a one-detector process.


Drop the datatype type that is automatically added, and get the Content-type type in this procedure
while (datatypes[0] = = "*") {
Datatypes.shift ();
if (ct = = undefined) {
ct = S.mimetype | | Jqxhr.getresponseheader ("Content-type");
}
}

Check if we're working on 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 one
Finaldatatype = Finaldatatype | | Firstdatatype;
}



Returns the correct response data


If we find a datatype
Put datatype in the datatypes, if you need to.
Returns the corresponding response data
if (Finaldatatype) {
if (Finaldatatype!== datatypes[0]) {
Datatypes.unshift (Finaldatatype);
}
return responses[Finaldatatype];
}
}




B. Type converters

Ajax has four different converters


Converters: {
Convert any content to a string
Window. String will be compressed into a.string in the min file
"* text": window. String,

Text to HTML (true means no conversion required, direct return)
' Text HTML ': true,

Convert text to JSON object
"Text json": Jquery.parsejson,

Convert Text to XML
"Text xml": Jquery.parsexml
}



Where Jquery.parsejson/jquery.parsexml click to see details

In addition, there are special extensions for the script


Ajax requests Set the default value
Jquery.ajaxsetup ({
/**
* Content Type Send request header (Content-type), which notifies the server what type of return result the request needs to receive.
* If the accepts setting needs to be modified, it is recommended to be set 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;
}
}


And one that was added at the time of Jsonp preprocessing.

s.converters["script json" = function () {
if (!responsecontainer) {
Jquery.error (Callbackname + "is not called");
}
return responsecontainer[0];
};


DataType is nothing more than a few things

1:datatype is empty, automatic conversion

In this case jquery can only guess the type of current need to be processed based on message header information (ajaxhandleresponses)


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


Get the message header information by Xhr.getallresponseheaders () and then match the value of all Content-type objects

Of course to 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 (ajaxhandleresponses)


See if we can handle the content-type, such as the image of the binary type is not good to deal with
if (CT) {
The text, XML, and JSON can actually be handled
For (type in contents) {
if (Contents[type] && contents[type].test (CT)) {
Datatypes.unshift (type);
Break
}
}
}

After this process, datatypes would have become the corresponding HTML, this is the internal jquery automatic conversion process.


2:datatype Developer Designation

XML, JSON, script, HTML, JSOP


Finally, the Ajax succeeds in calling the Ajaxconvert function processing. So the converter sums up a word: The type converter converts the ResponseText or responsexml of the server-side response to the data type specified at the request datatype, and automatically processes the response header Content-type if no type is specified. Converts a converter that chooses a response from the target type to the target data.
 
c. JQuery ajaxsetup (target[, Settings])

function if used for external use there is no settings for this parameter: the global default setting for Ajax.

This function has two usages

1. When target, settings two parameters are passed, create a fully fledged set object (including Ajaxsettings and delivery settings) written to target. The final jquery.ajaxsettings of this global variable has not changed. This usage is mainly jquery internal use, outside use is meaningless.
2. When the settings do not exist (that is, there is only one parameter), Target is written to jquery.ajaxsettings. This usage is used more externally. The main setting is to set the global default setting for Ajax.

Create a fully fledged set object (containing Ajaxsettings and delivery settings) written to target.
If the settings are omitted, target is written to ajaxsettings.
Ajaxsetup:function (target, settings) {
return settings?
Ajaxextend (Ajaxextend (target, jquery.ajaxsettings), settings):
Ajaxextend (jquery.ajaxsettings, target);
}


Using the Ajaxextend function, specify those options through JQuery.ajaxSettings.flatOptions without deep expansion (deep copy substitution), and all others to expand in depth. The default option for no depth expansion is only two jQuery.ajaxSettings.flatOptions: {url:true,context:true}. Externally, you can add an option that does not extend the depth directly to the jQuery.ajaxSettings.flatOptions.


Specialized extension functions for AJAX options
Options inside the flatoptions (No deep expansion (deep copy replacement) is required
function ajaxextend (target, SRC) {
var deep, Key,
flatoptions = JQuery.ajaxSettings.flatOptions | | {};

For options that do not require deep expansion in Target[key], the options for deep expansion are saved in Deep[key].
For (key in SRC) {
if (src[key]!== undefined) {
(flatoptions[key]? Target: (Deep | | (deep = {})) ) [Key] = src[key];
}
}
Depth expansion of content in deep (replacement of deep copy) to target
if (deep) {
Jquery.extend (True, target, deep);
}
return target;
}



D. Ajax-related APIs

Jquery.get (URL [, data] [, success] [, type]) (a function is used to obtain remote data from an AJAX request in HTTP GET form.)

The Jquery.get () function is used to implement a simple get-form Ajax request, which is implemented using Jquery.ajax () at the bottom, but omits most of the infrequently used parameter settings and is limited to HTTP GET mode. Note that the function loads the data asynchronously. The Jquery.get () described here is a global approach (you can call it without creating a jquery object, as you would think, as a static function). jquery also has an instance method get () with the same name that gets the DOM element that matches the specified index in the current jquery object. )

Jquery.post (URL [, data] [, success] [, type]) (a function is used to obtain remote data from an AJAX request in HTTP POST form.)

The Jquery.post () function is used to implement a simple post-form Ajax request, which is implemented using Jquery.ajax () at the bottom, but omits most of the infrequently used parameter settings and is limited to the HTTP POST method. Note that the function is loading data asynchronously.

Jquery.getjson (URL [, data] [, success]) (the function is used to obtain remote JSON-encoded data through an AJAX request in HTTP GET form.) JSON is a data format, JS native support JSON format, through the Jquery.getjson () from the server to obtain the JSON data, jquery will first try to convert it to the corresponding JS object. If the requested URL includes the "callback=?" And so on, jquery automatically sees it as JSONP and executes the corresponding callback function to get the JSON data.

Important NOTE: The JSON data returned by the server must conform to the strict JSON syntax, for example: all property names must be double quotes, and all string values must have double quotes (instead of single quotes). Note that the function loads the data asynchronously. )

Jquery.getscript (URL [, success]) (the function is used to load a JavaScript file in HTTP Get form 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 a cross-domain js file. Note that the function is loading data asynchronously.

JQuery.fn.load (URL [, data] [, complete]) (the function is used to load data from the server and replaces the contents of the current matching element with the returned HTML content.) The load () function uses the Get method by default and automatically reverts to post if data is provided in the form of an object. The load () function replaces only the internal content of each matching element (InnerHTML), so he defaults datatype to HTML. You can also append the specified selector (separated by a space) to the URL string to replace the contents of the current matching element with only a portion of the matching selector in the loaded HTML document. If the document does not match the contents of the selector, an empty string ("") is used to replace the contents of the current matching element.

If the current jquery object does not match any elements, the remote load request is not executed.

The load () described here is an AJAX request function, and in jquery there is an event function load () with the same name that executes the specified function when the document load completes. This function belongs to the jquery object (instance). This function is based on function Jquery.ajax () at the bottom.

Jquery.ajaxprefilter ([DataType,] handler) (function is used to specify a callback function that handles AJAX parameter options beforehand.) Before all parameter options are processed by the Jquery.ajax () function, you can use the callback function set by the function to change any parameter options beforehand.

You can also specify the data type (DataType) so that only the parameter options for the specified data type are processed beforehand. This function can be invoked more than once 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 argument is not specified, all data types are represented. The available data types are "XML", "HTML", "text", "JSON", "JSONP", "script". The string is any combination between them (many types are separated by spaces), such as "xml", "Text HTML", "script json Jsonp".

Handler (function type)

The callback function to use for preprocessing parameter options. It has the following 3 parameters:

Options: (Object object) all parameter options for the current AJAX request.

Originaloptions: (Object objects) an unmodified parameter option passed to the $.ajax () method.

JQXHR: The currently requested JQXHR object (XMLHttpRequest object that is encapsulated by jquery).





Jquery.ajaxsetup (Settingsobj) (functions are used to set the global default settings for Ajax.) This function is used to change the default setting options for AJAX requests in jquery. All AJAX requests that are subsequently executed, and if the corresponding option parameters are not set, the changed default settings are used. )



JQuery.fn.serialize () (function is used to serialize a set of form elements to encode the form content as a string for submission.) The serialize () function is often used to serialize the contents of a form for use in AJAX submissions.

This function is based primarily on the name and value of a valid form control used for submission, which is spliced into a text string that can be used directly with the form submission, which has been processed by standard URL encoding (character set encoding UTF-8).

The function does not serialize form controls that do not need to be committed, which is consistent with the normal form submission behavior. For example, a form control that is not in the <form> label will not be committed, a form control without a Name property will not be committed, a form control with the disabled property will not be committed, and a form control that is not selected will not be committed.

Unlike regular form submissions, a regular form typically submits a button control with name, and the serialize () function does not serialize a button control with name. )


JQuery.fn.serializeArray () (function is used to serialize a set of form elements and encode the form contents into a JavaScript array.) Often used to serialize a form's content into a JSON object so that it can be encoded as a string in JSON format.

The function encapsulates each form control that is available for submission to an object that has the name and Value property and the name and Value property of the form control. The object objects are then encapsulated into an array and returned.

The function does not serialize form controls that do not need to be committed, which is consistent with the normal form submission behavior. For example, a form control that is not in the <form> label will not be committed, a form control without a Name property will not be committed, a form control with the disabled property will not be committed, and a form control that is not selected will not be committed.

Unlike regular form submissions, a regular form typically submits a button control with name, and the Serializearray () function does not serialize a button control with name. )


Jquery.param (obj [, traditional]) (serializes a JS array or pure object into a string value for use in URL query strings or AJAX requests.) Returns an empty string ("") if the passed in is not an array or "pure object", or a direct error if the passed-in value of the property is null, undefined, and so on.

The so-called "pure object" is the object created by {} or New object (). JS built-in Boolean, number, String, Date, RegExp, Function, window and other types of objects are not "pure object."

The returned string has been processed by URL encoding (the character set used is UTF-8))

JQuery.fn.ajaxStart (HANDLERFN) (Ajaxstart event binding handler function for AJAX requests)

JQuery.fn.ajaxSend (HANDLERFN) (sets the callback function to execute when an AJAX request is about to be sent.) )

JQuery.fn.ajaxComplete (HANDLERFN) (sets the callback function that is executed when the AJAX request completes, regardless of success or failure). )

JQuery.fn.ajaxSuccess (HANDLERFN) (sets the callback function to execute when an AJAX request completes successfully.) )

JQuery.fn.ajaxError (HANDLERFN) (sets the callback function to execute when an AJAX request fails.) )

JQuery.fn.ajaxStop (HANDLERFN) (Ajaxstop event binding handler function for AJAX requests.) )

  



jquery ajax-without-response data solution

$.ajax ({

Type: "POST",

URL: "/membercomment.aspx/getordertobecommentcount",

Success:function (Result) {

Todo:

})

When using JS also did not error. This is the most depressing thing for me. I don't know what's wrong.



From C # code to browser to troubleshoot problems found all OK.

The reason for the final question is that the following is OK, with 2 fewer attributes:


$.ajax ({

Type: "POST",

ContentType: "Application/json",

URL: "/membercomment.aspx/getordertobecommentcount",

Data: "{A: ' A '}",

Success:function (Result) {

Todo:

}
})

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.