Home > Article > Web Front-end > Detailed explanation of synchronization processing of $.ajax() and $.getJson() in jQuery_jquery
1. Foreword
Why synchronization is needed? 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 in order from top to bottom. , if you perform an asynchronous operation during this process, you will not be able to obtain the result returned by the current asynchronous operation, and js will continue to execute the next statement, so we need to synchronize the operation request to obtain the background return data result, and then determine whether the result is consistent before executing. js next statement.
2. Explanation of $.ajax() parameters
url: The address to send the request.
type: The request method (post or get) defaults to get.
timeout: requires a parameter of type Number and sets the request timeout (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 synchronization operation
cache: The default is true. If the browser has a cache, the browser’s cached data will be obtained. Setting false will not obtain the cached data
data: Requires parameters of type Object or String, data sent to the server. If it is not a string, it will be automatically converted into a string format
Formula. The get request will be appended to the url. To prevent this automatic conversion, check the processData option. The object must be in key/value format
Formula, for example, {foo1:"bar1",foo2:"bar2"} is converted to &foo1=bar1&foo2=bar2. If it is an array, JQuery will automatically be different
Values correspond to the same name. For example, {foo:["bar1","bar2"]} is converted to &foo=bar1&foo=bar2.
dataType: requires a parameter of String type, the data type expected to be returned by the server. If not specified, JQuery will automatically base the http package on mime
The information returns responseXML or responseText and is passed as a callback function parameter.
The available types are as follows:
xml: Returns an XML document that can be processed with 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 cached automatically. Unless cache parameters are set. Note that when making remote requests (not under the same domain), all post requests will be converted into get requests.
json: Returns JSON data.
jsonp: JSONP format. When calling a function using the 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 Function type. You can modify the function of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. If false is returned in beforeSend, this ajax request can be canceled. The XMLHttpRequest object is the only parameter.
function(XMLHttpRequest){
This; //The options parameter passed when calling this ajax request
}
complete: requires a parameter of Function type, a callback function called after the request is completed (called when the request succeeds or fails). Parameters: XMLHttpRequest object and a string describing the successful request type.
function(XMLHttpRequest, textStatus){
This; //The options parameter passed when calling this ajax request
}
success: requires parameters of Function type. 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: requires a parameter of Function type, a function that is called when the request fails. This function has three parameters, namely XMLHttpRequest object, error message, and captured error object (optional).
The ajax event function is as follows:
function(XMLHttpRequest, textStatus, errorThrown){
//Normally, only one of textStatus and errorThrown contains information
This; //The options parameter passed when calling this ajax request
}
contentType: requires a parameter of 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: requires parameters of Function type, a function that preprocesses 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: is required to be a Boolean type parameter, and the default is true. Indicates whether to trigger the global ajax event. Setting to false will not trigger global ajax events, ajaxStart or ajaxStop can be used to control various ajax events.
ifModified: requires a Boolean type parameter, and the default is false. Only get new data when server data changes. The basis for determining server data changes is the Last-Modified header information. The default value is false, which means header information is ignored.
jsonp: requires parameters of String type, and rewrites the name of the callback function in a jsonp request. This value is used to replace the "callback" part of the URL parameter in a GET or POST request such as "callback=?". For example, {jsonp:'onJsonPLoad'} will cause "onJsonPLoad=?" to be passed to the server.
username: is required to be a String type parameter, used to respond to the username of the HTTP access authentication request.
password: requires a String type parameter, which is the password used to respond to the HTTP access authentication request.
processData: requires a Boolean type parameter, and the default is true. By default, the data sent will be converted to an object (not technically a string) to match the default content type "application/x-www-form-urlencoded". If you want to send DOM tree information or other information that you do not want to convert, set it to false.
scriptCharset: is required to be a String type parameter. It will be used to force the character set (charset) to be modified only when the dataType is "jsonp" or "script" during the request, and the type is GET. Usually used when the local and remote content encodings are different.
3. $.getJson() synchronization settings
$.getJson() itself is an asynchronous operation method and needs to be set up before it can be synchronized
Add $.ajaxSettings.async = false; (synchronous execution) before execution. After executing your code, return to $.ajaxSettings.async = true in time; (asynchronous execution) otherwise it will affect the code in other places that needs to be executed asynchronously. .
4. Specific operation examples
1. $.ajax()
//点击新增按钮,新增数据 $("#btnAdd").click(function () { var bool = true;//存储异步请求结果是否通过 //1、验证优惠额度正确性 var index = parseInt($("#intGiftMold").val()); if (index == 1) { //满减 var reg = /^[0-9]+,[0-9]+$/; if (!reg.test($("#strDiscounts").val())) { $.messager.alert('错误提示', '满减优惠额度格式不正确', 'error'); return false; } } else if (index == 2) { var reg = /^0\.[0-9]+$/; if (!reg.test($("#strDiscounts").val())) { $.messager.alert('错误提示', '折扣优惠额度格式不正确', 'error'); return false; } } else if (index == 3) { var reg = /^[1-9]+[0-9]$/; if (!reg.test($("#strDiscounts").val())) { $.messager.alert('错误提示', '指定金额优惠额度格式不正确', 'error'); return false; } } //2、验证优惠范围正确性 var index = parseInt($("#intGiftRange").val()); if (index == 1) { //选择全站 } else if (index == 3) { //判断商品ID $.ajax({ type: "post", url: "Gift_Add.aspx", cache: false, async: false, //设置同步了~~~~~~~~~ dataType: "json", data: { "method": "isExistInfoTitle", "intInfoID": $("#intInfoID").val() }, success: function (data) { if (data.result == "false") { $.messager.alert('错误提示', '商品ID不存在', 'error'); bool = false; $("#isExistInfoTitle").css({ "display": "" }); } else { $("#isExistInfoTitle").css({ "display": "none" }); bool = true; } } }); } }); } if (bool == false) {//如果bool为false才返回,true继续往下走 return false; //不能在异步方法里面return,不起作用 } var validate = $("#form").form("validate"); if (!validate) {//表单验证不通过 return false; } //当上面全部验证通过了执行新增操作 $.messager.confirm('温馨提示', '是否确认添加', function (r) { if (r) { $.post("Gift_Add.aspx?method=addGift", $("#form").serialize(), function (data) { $.messager.alert('成功提示', '添加成功', 'info'); }); } }); });
2. $.getJson()
//点击新增按钮,新增数据 $("#btnAdd").click(function () { var bool = true;//存储异步请求结果是否通过 //1、验证优惠额度正确性 var index = parseInt($("#intGiftMold").val()); if (index == 1) { //满减 var reg = /^[0-9]+,[0-9]+$/; if (!reg.test($("#strDiscounts").val())) { $.messager.alert('错误提示', '满减优惠额度格式不正确', 'error'); return false; } } else if (index == 2) { var reg = /^0\.[0-9]+$/; if (!reg.test($("#strDiscounts").val())) { $.messager.alert('错误提示', '折扣优惠额度格式不正确', 'error'); return false; } } else if (index == 3) { var reg = /^[1-9]+[0-9]$/; if (!reg.test($("#strDiscounts").val())) { $.messager.alert('错误提示', '指定金额优惠额度格式不正确', 'error'); return false; } } //2、验证优惠范围正确性 var index = parseInt($("#intGiftRange").val()); if (index == 1) { //选择全站 } else if (index == 3) { //判断商品ID $.ajaxSettings.async = false; //设置getJson同步 $.getJSON("Gift_Add.aspx", { "method": "isExistInfoTitle", "intInfoID": $("#intInfoID").val() }, function (data) { if (data.result == "false") { $.messager.alert('错误提示', '商品ID不存在', 'error'); bool = false; $("#isExistInfoTitle").css({ "display": "" }); } else { $("#isExistInfoTitle").css({ "display": "none" }); bool = true; } }); $.ajaxSettings.async = true;//设置getJson异步 } }); } if (bool == false) {//如果bool为false才返回,true继续往下走 return false; //不能在异步方法里面return,不起作用 } var validate = $("#form").form("validate"); if (!validate) {//表单验证不通过 return false; } //当上面全部验证通过了执行新增操作 $.messager.confirm('温馨提示', '是否确认添加', function (r) { if (r) { $.post("Gift_Add.aspx?method=addGift", $("#form").serialize(), function (data) { $.messager.alert('成功提示', '添加成功', 'info'); }); } }); });
Summary:
$.ajax is the AJAX implementation of the traditional get and post methods
$.getJSON is jsonp (remote data reading) class AJAX implementation
The reason why it is called AJAX-like is that 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:
When sending, $.getJSON will pass a callback function name (jq will give one by default)
When receiving, this callback function will be called
The server side of $.getJSON must append the incoming callback function name before the json data
Because of this, the returned string is no longer json (the format is wrong)
Therefore $.ajax with dataType: "json" attribute will enter the error branch