Detailed explanation of synchronous processing of $.ajax() and $.getJson() in jQuery

This article mainly introduces the relevant information about the synchronous processing of $.ajax() and $.getJson() in jQuery, which is very detailed and comprehensive, and friends who need it can refer to it.
1. Introduction

Why do we need to use synchronization, because sometimes when we register a submit button to submit form data, a series of asynchronous ajax request operations will be performed before the submission action, but the page js code will be executed sequentially from top to bottom , if you perform an asynchronous operation during this process, then the result returned by the current asynchronous operation cannot be obtained, and js will continue to execute the next statement, so we need to synchronously operate the request to obtain the data result returned by the background, and then judge whether the result is in line with the execution. js next statement.

Second, $.ajax () parameter explanation

url: The address to send the request.

type: The request method (post or get) defaults to get.

timeout: The request is a parameter of type Number, which sets the request timeout time (milliseconds).

async: The default setting is true, all requests are asynchronous requests. Synchronous request, set to false. Note that a synchronous request will lock the browser, and the user must wait for the request to complete before other operations can be performed. -----This is the most important setting factor for synchronous operation

cache: the default is true, if the browser has a cache, it will get the cached data of the browser, and if it is set to false, how can it not get the cached data

data: it is required to be of type Object or String parameters, the data sent to the server. If it is not a string, it will be automatically converted to string

      format . The get request will be appended to the url. To prevent this automatic conversion, look at the processData option. Object must be in key/value format

      formula, such as {foo1:"bar1",foo2:"bar2"} is converted to &foo1=bar1&foo2=bar2. If it is an array, JQuery will automatically assign different

      values ​​to the same name. For example {foo:["bar1","bar2"]} translates to &foo=bar1&foo=bar2.

dataType: The parameter required to be of type String, the expected data type returned by the server. If not specified, JQuery will automatically

          return responseXML or responseText according to the http package mime information, and pass it as a callback function parameter.

          The available types are as follows:

          xml: Returns an XML document that can be processed by JQuery.

          html: Returns plain text HTML information; the included script tag will be executed when inserted into the DOM.

          script: Returns plain text JavaScript code. Results are not automatically cached. Unless the cache parameter is set. Note that when making remote requests (not under the same domain), all post requests will be converted to get requests.

          json: Returns JSON data.

          jsonp: JSONP format. When calling a function in SONP form, such as myurl?callback=?, JQuery will automatically replace the last "?" with the correct function name to execute the callback function.

          text: Returns a plain text string.

beforeSend: requires a parameter of type Function, which can modify the function of the XMLHttpRequest object before sending the request, such as adding custom HTTP headers. If you return false in beforeSend, you can cancel this ajax request. The XMLHttpRequest object is the only parameter.

            function(XMLHttpRequest){
                this; //The options parameter passed when calling this ajax request
             }

complete: The parameter is required to be a Function type, and the callback function to be called after the request is completed (called when the request succeeds or fails). Parameters: XMLHttpRequest object and a string describing the type of successful request.

          function(XMLHttpRequest, textStatus){
              this; //The options parameter passed when calling this ajax request
           }

success: The parameter required to be Function type, the callback function called after the request is successful, there are two parameters.

         (1) The data returned by the server and processed according to the dataType parameter.

         (2) A string describing the state.

         function(data, textStatus){

            //data may be xmlDoc, jsonObj, html, text, etc. this;

           //The options parameter passed when calling this ajax request

error: the parameter is required to be a Function type, and the function to be called when the request fails. This function has 3 parameters, namely XMLHttpRequest object, error message, captured error object (optional).

       The ajax event function is as follows:

       function(XMLHttpRequest, textStatus, errorThrown){
           //Usually only one of textStatus and errorThrown contains information
           this; //The options parameter passed when calling this ajax request
        }

contentType: The parameter required to be String type , when sending information to the server, the content-encoding type defaults to "application/x-www-form-urlencoded". This default value is suitable for most applications.

dataFilter: A function that requires a parameter of type Function to preprocess the original data returned by Ajax. Provide two parameters data and type. data is the original data returned by Ajax, and type is the dataType parameter provided when calling jQuery.ajax. The value returned by the function will be further processed by jQuery.

            function(data, type){
                 //return the processed data
                 return data;
             }

global: requires a parameter of type Boolean, the default is true. Indicates whether to trigger the global ajax event. Set to false will not trigger global ajax events, ajaxStart or ajaxStop can be used to control various ajax events.

ifModified: The parameter is required to be a Boolean type, the default is false. Only get new data when server data changes. The server data change judgment is based on the Last-Modified header information. The default value is false, which ignores the header information.

jsonp: Requires a parameter of type String, and rewrites the name of the callback function in a jsonp request. This value is used in place of the "callback" part of the URL parameter in a GET or POST request such as "callback=?", e.g. {jsonp:'onJsonPLoad'} will cause "onJsonPLoad=?" to be passed to the server.

username: The parameter required to be of type String is the username used to respond to the HTTP access authentication request.

password: The parameter required to be of type String is the password used to respond to the HTTP access authentication request.

processData: The parameter is required to be a Boolean type, and the default is true. By default, sent data will be converted to an object (technically not a string) to match the default content type "application/x-www-form-urlencoded". Set to false if you want to send DOM tree information or other information that you don't want to convert.

scriptCharset: A parameter required to be of type String. Only when the dataType is "jsonp" or "script" and the type is GET will it be used to forcibly modify the character set (charset). Typically used when the local and remote content encodings are different.

Three, $.

$.getJson() itself is a method of asynchronous operation, and it needs to be set to be synchronous.

Before execution, add $.ajaxSettings.async = false; (synchronous execution) After executing your code, restore to $.ajaxSettings.async = true in time; (Asynchronous execution) Otherwise, code that needs to be executed asynchronously elsewhere will be affected.

Fourth, the specific operation example

1, $.ajax ()
//Click the add button to add new data     
 $("#btnAdd").click(function () {        
var bool = true;//Store whether the asynchronous request result is passed       
 //1. Verify the correctness of the discount amount        
var index = parseInt($("#intGiftMold").val());       
 if (index == 1) {         
 // full reduction          
var reg = / ^ [0-9] +, [0-9] + $ /;         
 if (!reg.test($("#strDiscounts").val())) { $.messager.alert('Error message', 'The format of the full discount amount is incorrect', 'error');            
return false;          
}        
}        
else if (index == 2) {         
 var reg = /^0\.[0-9]+$/;          
if (!reg.test($("#strDiscounts").val())) { $.messager.alert('Error message', 'The format of the discount amount is incorrect', 'error');            
return false;          
}        
}       
 else if (index == 3) {         
 var reg = / ^ [1-9] + [0-9] $ /;         
 if (!reg.test($("#strDiscounts").val())) { $.messager.alert('Error message', 'The format of the specified amount discount amount is incorrect', 'error');            
return false;          
}        
}       
 //2. Verify the correctness of the discount range       
 var index = parseInt($("#intGiftRange").val());        
if (index == 1) {
//select the whole station       
 }        
else if (index == 3) {  
//Determine 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) {//If bool is false to return, true continue to go down return false;  
//Can't return in an asynchronous method, it doesn't work       
 }       
 var validate = $("#form").form("validate");       
 if (!validate) {//Form validation failed         
 return false;       
 }       
 //When all the above verifications are passed, execute the new operation       
 $.messager.confirm('Warm reminder', 'Confirm to add', function (r) {         
 if (r) {           
 $.post("Gift_Add.aspx?method=addGift", $("#form").serialize(), function (data) {             
 $.messager.alert('Successful prompt', 'Added successfully', 'info');            
});         
 }       
 });   
   });


$.getJson()
//Click the add button to add new data     
$("#btnAdd").click(function () {       
var bool = true;//Store whether the asynchronous request result is passed       
//1. Verify the correctness of the discount amount       
var index = parseInt($("#intGiftMold").val());       
if (index == 1) {         
// full reduction         
var reg = / ^ [0-9] +, [0-9] + $ /;         
if (!reg.test($("#strDiscounts").val())) { $.messager.alert('Error message', 'The format of the full discount amount is incorrect', 'error');           
return false;         
}       
}       
else if (index == 2) {         
var reg = /^0\.[0-9]+$/;         
if (!reg.test($("#strDiscounts").val())) { $.messager.alert('Error message', 'The format of the discount amount is incorrect', 'error');           
return false;         
}       
}       
else if (index == 3) {         
var reg = / ^ [1-9] + [0-9] $ /;         
if (!reg.test($("#strDiscounts").val())) { $.messager.alert('Error message', 'The format of the specified amount discount amount is incorrect', 'error');           
return false;         
}       
}       
//2. Verify the correctness of the discount range       
var index = parseInt($("#intGiftRange").val());       
if (index == 1) {
//select the whole station       
}       
else if (index == 3) {  
//Determine the product ID          
$.ajaxSettings.async = false; //Set getJson synchronization         
$.getJSON("Gift_Add.aspx", { "method": "isExistInfoTitle", "intInfoID": $("#intInfoID").val() }, 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;           
}         
});         
$.ajaxSettings.async = true;//Set getJson asynchronous       
}        
 });       
}       
if (bool == false)
{//If bool is false to return, true continues to go down         
return false;  
//Can't return in an asynchronous method, it doesn't work       
}       
var validate = $("#form").form("validate");       
if (!validate) {//Form validation failed         
return false;       
}       
//When all the above verifications are passed, execute the new operation      
 $.messager.confirm('Warm reminder', 'Confirm to add', function (r) { if (r) {           
$.post("Gift_Add.aspx?method=addGift", $("#form").serialize(), function (data) {             
$.messager.alert('Successful prompt', 'Added successfully', 'info');           
});         
}       
});     
});

Summary:

$.ajax is the AJAX implementation of the traditional get and post methods
$.getJSON is the jsonp (remote data read) class AJAX implementation
  is called class AJAX because although it is encapsulated in jq's ajax class, the actual It is implemented through the script node

. The difference between $.getJSON and $.ajax is:


when sending, $.getJSON will pass a callback function name (by default, jq will give one). When
  receiving, this callback function will be called by The server that calls
$.getJSON must append the incoming callback function name to the json data.
  Because of this, the returned string is no longer json (the format is wrong),
  so there is a $.ajax with the attribute dataType:"json" will enter the error branch due to json parsing errors

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326512150&siteId=291194637