This article mainly introduces the detailed information about $. ajax () and $. getJson () Synchronization processing in jQuery, which is very detailed and comprehensive. If you need it, you can refer to it.
I. Preface
Why do we need to use synchronization? Sometimes, when we register a submission button to submit form data, a series of asynchronous ajax request operations will be performed before the submission action, however, the page js Code will be executed from top to bottom in order. If you perform asynchronous operations in this process, the result returned by the current asynchronous operation will not be obtained, and js will continue to execute the next statement, therefore, we need to synchronize the operation request to obtain the data returned by the background, and then execute the next js statement to determine whether the result meets the requirements.
Ii. $. ajax () parameter explanation
Url:The address where the request is sent.
Type:The request method (post or get) is get by default.
Timeout:Set the request timeout time (in milliseconds) for a Number parameter ).
Async:The default value is true. All requests are asynchronous requests. Synchronous request, set to false. Note: The synchronous request locks the browser. Other operations can be performed only after the request is completed. ----- This is the most important setting factor for synchronization operations
Cache:The default value is true. If the browser has a cache, the browser will obtain the cache data. If it is set to false, how can it not obtain the cache data?
Data:The data sent to the server must be of the Object or String type. If it is no longer a string, it is automatically converted to a string
. The get request will be appended to the url. To prevent this automatic conversion, you can view the processData option. The object must be in the key/value format.
Format. For example, {foo1: "bar1", foo2: "bar2"} is converted to & foo1 = bar1 & foo2 = bar2. If it is an array, JQuery will automatically be different
The value corresponds to the same name. For example, {foo: ["bar1", "bar2"]} is converted to & foo = bar1 & foo = bar2.
DataType:It must be a String parameter. The data type returned by the server is expected. If this parameter is not specified, JQuery automatically uses the http package mime
ResponseXML or responseText is returned and passed as the callback function parameter.
The available types are as follows:
Xml: the XML document is returned and can be processed by JQuery.
Html: returns plain text HTML information. The included script tag is executed when the DOM is inserted.
Script: returns plain text JavaScript code. Results are not automatically cached. Unless the cache parameter is set. Note that during remote requests (not in the same domain), all post requests will be converted to get requests.
Json: Return JSON data.
Jsonp: JSONP format. When a function is called in the form of SONP, such as myurl? Callback = ?, JQuery will automatically Replace the last "?" For the correct function name to execute the callback function.
Text: returns a plain text string.
BeforeSend:A parameter of the Function type is required. Before sending a request, you can modify the Function of the XMLHttpRequest object, for example, adding a custom HTTP header. In beforeSend, if false is returned, the ajax request can be canceled. The XMLHttpRequest object is a unique parameter.
Function (XMLHttpRequest ){
This; // The options parameter passed when calling this ajax request
}
Complete:A parameter of the Function type is required. The callback Function called after the request is complete (called when the request is successful or fails ). Parameter: XMLHttpRequest object and a string that describes the successful request type.
Function (XMLHttpRequest, textStatus ){
This; // The options parameter passed when calling this ajax request
}
Success:A parameter of the Function type is required. The callback Function called after the request is successful has two parameters.
(1) data returned by the server and processed according to the dataType parameter.
(2) A string describing the status.
Function (data, textStatus ){
// Data may be xmlDoc, jsonObj, html, text, etc. this;
// The options parameter passed when calling this ajax request
Error:A parameter of the Function type is required. The Function called when the request fails. This function has three parameters: XMLHttpRequest object, error message, and captured error object (optional ).
Ajax event functions are as follows:
Function (XMLHttpRequest, textStatus, errorThrown ){
// Generally, textStatus and errorThrown only contain one of the information.
This; // The options parameter passed when calling this ajax request
}
ContentType:It must be a String parameter. When the message is sent to the server, the content encoding type is "application/x-www-form-urlencoded" by default ". This default value is suitable for most applications.
DataFilter:A Function that requires a Function type parameter to pre-process the original data returned by Ajax. Provides two parameters: data and type. Data is the original data returned by Ajax, and type is the dataType parameter provided when jQuery. ajax is called. The value returned by the function will be further processed by jQuery.
Function (data, type ){
// Return the processed data
Return data;
}
Global:It must be a Boolean parameter. The default value is true. Indicates whether to trigger a global ajax event. Setting false does not trigger global ajax events. ajaxStart or ajaxStop can be used to control various ajax events.
IfModified:It must be a Boolean parameter. The default value is false. Obtain New data only when the server data changes. The server data change judgment is based on the Last-Modified header information. The default value is false, indicating that the header information is ignored.
Jsonp:A parameter of the String type is required. The name of the callback function is rewritten in a jsonp request. This value is used to replace "callback =? "Callback" in the URL parameter of this GET or POST request, for example, {jsonp: 'onjsonpload'} causes "onJsonPLoad =? "To the server.
Username:A String-type parameter is required. It is the username used to respond to the HTTP access authentication request.
Password:It must be a String type parameter, used to respond to the password of the HTTP access authentication request.
ProcessData:It must be a Boolean parameter. The default value is true. By default, the sent data will be converted to an object (technically not a string) to work with the default content type "application/x-www-form-urlencoded ". If you want to send DOM tree information or other information that does not want to be converted, set it to false.
ScriptCharset:A parameter of the String type is required. It is used to force charset modification only when dataType is "jsonp" or "script" and type is GET ). Generally, the local and remote content encoding is not used at the same time.
3. $. getJson () Synchronization settings
$. GetJson () is an asynchronous operation method and can be synchronized only after being set.
Add $. ajaxSettings. async = false; (synchronous execution) after you execute your code, restore to $ in time. ajaxSettings. async = true; (asynchronous execution) otherwise, the code to be asynchronously executed elsewhere will be affected.
Iv. Specific operation examples
1. $. ajax ()
// Click Add to add data $ ("# btnAdd "). click (function () {var bool = true; // store whether the asynchronous request result passes // 1. verify the validity of the discount amount var index = parseInt ($ ("# intGiftMold "). val (); if (index = 1) {// var reg =/^ [0-9] +, [0-9] + $ /; if (! Reg. test ($ ("# strDiscounts "). val () {$. messager. alert ('error prompting ', 'incorrect full discount quota format', 'error'); return false ;}} else if (index = 2) {var reg =/^ 0 \. [0-9] + $/; if (! Reg. test ($ ("# strDiscounts "). val () {$. messager. alert ('error message', 'incorrect discount quota format ', 'error'); return false ;}} else if (index = 3) {var reg =/^ [1-9] + [0-9] $/; if (! Reg. test ($ ("# strDiscounts "). val () {$. messager. alert ('error message', 'incorrect format of the specified amount of preferential free', 'error'); return false ;}} // 2. verify the validity of the offer range var index = parseInt ($ ("# intGiftRange "). val (); if (index = 1) {// select full site} else if (index = 3) {// judge the product ID $. ajax ({type: "post", url: "Gift_Add.aspx", cache: false, async: false, // The settings are synchronized ~~~~~~~~~ DataType: "json", data: {"method": "isExistInfoTitle", "intInfoID": $ ("# intInfoID "). val ()}, success: function (data) {if (data. result = "false") {$. messager. alert ('error message', 'item ID does not exist', 'error'); bool = false; $ ("# isExistInfoTitle" ..css ({"display ": ""}) ;}else {$ ("# isExistInfoTitle" ).css ({"display": "none "}); bool = true ;}}) ;}}) ;}if (bool = false) {// return if bool is false, true continues to return False; // return cannot be returned in the Asynchronous Method and does not work} var validate = $ ("# form"). form ("validate"); if (! Validate) {// Form Verification Failed return false;} // when all the above verification has passed the new operation $. messager. confirm ('tips ', 'Are you sure you want to add', function (r) {if (r) {$. post ("Gift_Add.aspx? Method = addGift ", $ (" # form "). serialize (), function (data) {$. messager. alert ('success prompt ', 'added successfully', 'info ');});}});});
2. $. getJson ()
// Click Add to add data $ ("# btnAdd "). click (function () {var bool = true; // store whether the asynchronous request result passes // 1. verify the validity of the discount amount var index = parseInt ($ ("# intGiftMold "). val (); if (index = 1) {// var reg =/^ [0-9] +, [0-9] + $ /; if (! Reg. test ($ ("# strDiscounts "). val () {$. messager. alert ('error prompting ', 'incorrect full discount quota format', 'error'); return false ;}} else if (index = 2) {var reg =/^ 0 \. [0-9] + $/; if (! Reg. test ($ ("# strDiscounts "). val () {$. messager. alert ('error message', 'incorrect discount quota format ', 'error'); return false ;}} else if (index = 3) {var reg =/^ [1-9] + [0-9] $/; if (! Reg. test ($ ("# strDiscounts "). val () {$. messager. alert ('error message', 'incorrect format of the specified amount of preferential free', 'error'); return false ;}} // 2. verify the validity of the offer range var index = parseInt ($ ("# intGiftRange "). val (); if (index = 1) {// select full site} else if (index = 3) {// judge the product ID $. ajaxSettings. async = false; // set getJson synchronization $. getJSON ("Gift_Add.aspx", {"method": "isExistInfoTitle", "intInfoID": $ ("# intInfoID "). val ()}, function (data) {if (data. resu Lt = "false") {$. messager. alert ('error message', 'item ID does not exist', 'error'); bool = false; $ ("# isExistInfoTitle" ..css ({"display ": ""}) ;}else {$ ("# isExistInfoTitle" ).css ({"display": "none"}); bool = true ;}}); $. ajaxSettings. async = true; // set getJson asynchronous});} if (bool = false) {// if bool is false, return is returned. true continues to return false; // return does not work in the Asynchronous Method.} var validate = $ ("# form "). form ("validate"); if (! Validate) {// Form Verification Failed return false;} // when all the above verification has passed the new operation $. messager. confirm ('tips ', 'Are you sure you want to add', function (r) {if (r) {$. post ("Gift_Add.aspx? Method = addGift ", $ (" # form "). serialize (), function (data) {$. messager. alert ('success prompt ', 'added successfully', 'info ');});}});});
Summary:
$. Ajax is the AJAX Implementation of the traditional get and post methods.
$. GetJSON is a jsonp (Remote Data Reading) AJAX implementation.
AJAX is called because although it is encapsulated in the ajax class of jq, it is actually implemented through the script node.
The difference between $. getJSON and $. ajax is as follows:
When sending, $. getJSON will pass a callback function name (A jq will be sent if there is a shortage of time)
Yes. This callback function will be called.
$. The getJSON server must append the passed callback function name to the json data.
Because of this, the returned string is no longer json (the format is incorrect)
Therefore, $. ajax with the dataType: "json" attribute will enter the error Branch due to a json parsing error.