First, the preface
Why do I need to use synchronization, because sometimes when we register a submit button to submit the form data, we do a series of asynchronous Ajax requests before submitting the action, but the page JS code executes sequentially from the top down, and if you do asynchronous operations in this process, Then get the results of the current asynchronous operation returned, JS will continue to execute the next statement, so we need to synchronize the operation request to get back to the results of the return data, to determine whether the results are consistent with the implementation of JS Next statement.
Two, $.ajax () parameter explanation
URL: The address where the request is sent.
type: the request method (post or get) defaults to get.
Timeout: requires a parameter of type number to set the request timeout (in milliseconds).
Async: The default setting is True, all requests are asynchronous requests. Sync request, set to False. Note that the synchronization request will lock the browser, and other actions must wait for the request to complete before it can be executed. -----This is the most important setup factor for sync operations
Cache : default to True, if the browser has a cache will get the browser's cached data, set false how does not get cached data
Data : requires an object or string type of parameter to be sent to the server. If it is no longer a string, it is automatically converted to a string lattice
Expression The GET request is appended to the URL. To prevent this automatic conversion, you can view the ProcessData option. The object must be Key/value
, such as {foo1: "Bar1", Foo2: "Bar2"} is converted to &FOO1=BAR1&FOO2=BAR2. If it is an array, jquery will automatically be different
Value corresponds to the same name. For example, {foo:["bar1", "Bar2"]} is converted to &FOO=BAR1&FOO=BAR2.
DataType: required for string type parameter, expected server returned data type. If not specified, jquery will automatically mime based on HTTP package
The information is returned to 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, and the included script tag executes when the DOM is inserted.
Script: Returns the plain text JavaScript code. Results are not automatically cached. Unless the cache parameter is set. Note that when a remote request is not in the same domain, all post requests are converted to get requests.
JSON: Returns JSON data.
JSONP:JSONP format. When calling a function using the Sonp form, for example, Myurl?callback=?,jquery will automatically replace the latter "?" To the correct function name to execute the callback function.
Text: Returns a plain text string.
Beforesend: requires a parameter of a function type, you can modify the function of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. If you return False in Beforesend, you can cancel this Ajax request. The XMLHttpRequest object is the only parameter.
function (XMLHttpRequest) {
This The options argument passed when invoking this Ajax request
}
Complete: A parameter that requires a function type that is invoked after the request completes (called when the request succeeds or fails). Parameters: XMLHttpRequest object and a string that describes the type of successful request.
function (XMLHttpRequest, textstatus) {
This The options argument passed when invoking this Ajax request
}
success: A parameter that requires a function type, and a callback function called after the success of the request, with 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, and so on this;
The options argument passed when invoking this Ajax request
Error: A function that requires a parameter of a function type that is called when a request fails. The function has 3 parameters, that is, an XMLHttpRequest object, an error message, a captured Error object (optional).
The Ajax event functions are as follows:
function (XMLHttpRequest, textstatus, Errorthrown) {
Usually only one of the Textstatus and Errorthrown contains information
This The options argument passed when invoking this Ajax request
}
ContentType: requires a String type parameter, the content encoding type defaults to "application/x-www-form-urlencoded" when sending information to the server. This default value is appropriate for most applications.
datafilter: A function that requires preprocessing of the original data returned by Ajax for parameters of the function type. Provides data and type two parameters. Data is the original source returned by Ajax, and type is the datatype parameter provided when the Jquery.ajax is invoked. The value returned by the function will be further processed by jquery.
function (data, type) {
Returns the processed data
return data;
}
Global: A parameter of a Boolean type is required, and the default is true. Indicates whether global AJAX events are triggered. Setting to FALSE will not trigger global AJAX events, Ajaxstart or ajaxstop can be used to control various AJAX events.
ifmodified: parameter required for Boolean type, default to False. Gets new data only when the server data changes. The server data change judgment is based on last-modified header information. The default value is False, which is to ignore header information.
JSONP: requires an argument of type string to override the name of the callback function in a JSONP request. This value is used in place of the "callback=?" The "callback" section of the URL parameter in this get or POST request, for example {jsonp: ' onjsonpload '}, causes the "onjsonpload=?" passed to the server.
Username: A parameter of type string that is required to respond to the user name of an HTTP access authentication request.
Password: A parameter of type string that is required to respond to the password for HTTP access authentication requests.
processdata: parameter required for Boolean type, default to True. By default, the data sent is converted to an object (not technically 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 do not want to convert.
scriptcharset: A parameter of type string is required to force the character set (charset) only when the request is datatype to "JSONP" or "script" and type is get. Typically used when local and remote content encodings are different.
Three, $.getjson () synchronization settings
$.getjson () itself is a method of asynchronous operation that needs to be set to be synchronized
Add $.ajaxsettings.async = False before execution; (synchronous execution) after executing your code in time to $.ajaxsettings.async = true; (execute asynchronously) otherwise affect the code that needs to be executed asynchronously elsewhere.
Iv. specific examples of operations
1, $.ajax ()
Click on the New button to add $ ("#btnAdd"). Click (function () {var bool = true;
//Storage Asynchronous request results through//1, verify the discount amount is correct
var index = parseint ($ ("#intGiftMold"). Val ());
if (index = = 1) {//full minus var reg =/^[0-9]+,[0-9]+$/;
if (!reg.test ($ ("#strDiscounts"). Val ())) {
$.messager.alert (' ERROR hint ', ' invalid format ' for full discount amount, ' Error ');
return false; } else if (index = = 2) {var reg =/^0\.[
0-9]+$/;
if (!reg.test ($ ("#strDiscounts"). Val ()) {
$.messager.alert (' ERROR hint ', ' the discount amount is not properly formatted ', ' Error ');
return false;
} else if (index = = 3) {var reg =/^[1-9]+[0-9]$/;
if (!reg.test ($ ("#strDiscounts"). Val ())) {
$.messager.alert (' ERROR hint ', ' specified amount of coupon format incorrect ', ' error ');
return false;
}//2, verify the concession range is correct var index = parseint ($ ("#intGiftRange"). Val ());
if (index = = 1) {//select Full Station} else if (index = = 3) {
//Judge commodity ID $.ajax ({type: Post), url: "Gift_add.aspx", Cache:false, Async:false,//Set sync ~~~~~~~~~ dataType: "JSON", Data: {
"method": "Isexistinfotitle", "Intinfoid": $ ("#intInfoID"). Val ()}, Success:function (data) {if (data.re
Sult = = "false") {$.messager.alert (' false hint ', ' Product ID not present ', ' Error ');
bool = false;
$ ("#isExistInfoTitle"). CSS ({"Display": ""});
else {$ (' #isExistInfoTitle '). CSS ({"Display": "None"});
BOOL = true;
}
}
});
}
}); if (bool = false) {//if BOOL is false to return, true continues to go down returns false;
Cannot return inside asynchronous method, does not work} var validate = $ ("#form"). Form ("Validate");
if (!validate) {//form validation does not pass return false;
//When all of the above validation has passed the Execute newOperation $.messager.confirm (' Warm prompt ', ' confirm add ', function (r) {
if (R) {$.post ("Gift_add.aspx?method
=addgift ", $ (" #form "). Serialize (), function (data) {$.messager.alert (' success hint ', ' add success ', ' info ');
});
}
});
});
// click the add button
$ ("# btnAdd"). click (function () {
var bool = true; // stores whether the result of the asynchronous request passes
// 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 limit is incorrect', 'error');
return false;
}
}
else if (index == 2) {
var reg = /^0\.[0-9]+$/;
if (! reg.test ($ ("# strDiscounts"). val ())) {
$ .messager.alert ('Error message', 'Incorrect format of discount offer amount', 'error');
return false;
}
}
else if (index == 3) {
var reg = / ^ [1-9] + [0-9] $ /;
if (! reg.test ($ ("# strDiscounts"). val ())) {
$ .messager.alert ('Error message', 'The specified amount of the discount amount is not in the correct format', 'error');
return false;
}
}
// 2 、 Verify the validity of the discount range
var index = parseInt ($ ("# intGiftRange"). val ());
if (index == 1) {// Select all stations
}
else if (index == 3) {// determine product ID
$ .ajax ({
type: "post",
url: "Gift_Add.aspx",
cache: false,
async: false, // Set the synchronization ~~~~~~~~~
dataType: "json",
data: {"method": "isExistInfoTitle", "intInfoID": $ ("# intInfoID"). val ()},
success: function (data) {
if (data.result == "false") {
$ .messager.alert ('Error message', 'Product ID does not exist', 'error');
bool = false;
$ ("# isExistInfoTitle"). css ({"display": ""});
}
else {
$ ("# isExistInfoTitle"). css ({"display": "none"});
bool = true;
}
}
});
}
});
}
if (bool == false) {// If bool is false, return, true continue to go down
return false; // Cannot return in asynchronous methods, does not work
}
var validate = $ ("# form"). form ("validate");
if (! validate) {// Form validation failed
return false;
}
// When all the above verifications pass, perform the new operation
$ .messager.confirm ('Warm reminder', 'Whether to confirm the addition', function (r) {
if (r) {
$ .post ("Gift_Add.aspx? method = addGift", $ ("# form"). serialize (), function (data) {
$ .messager.alert ('Success prompt', 'Successfully added', 'info');
});
}
});
});
2, $.getjson ()
// click the add button
$ ("# btnAdd"). click (function () {
var bool = true; // stores whether the result of the asynchronous request passes
// 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 limit is incorrect', 'error');
return false;
}
}
else if (index == 2) {
var reg = /^0\.[0-9]+$/;
if (! reg.test ($ ("# strDiscounts"). val ())) {
$ .messager.alert ('Error message', 'Incorrect format of discount offer amount', 'error');
return false;
}
}
else if (index == 3) {
var reg = / ^ [1-9] + [0-9] $ /;
if (! reg.test ($ ("# strDiscounts"). val ())) {
$ .messager.alert ('Error message', 'The specified amount of the discount amount is not in the correct format', 'error');
return false;
}
}
// 2 、 Verify the validity of the discount range
var index = parseInt ($ ("# intGiftRange"). val ());
if (index == 1) {// Select all stations
}
else if (index == 3) {// determine 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', 'Product 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, true continue to go down
return false; // Cannot return in asynchronous methods, does not work
}
var validate = $ ("# form"). form ("validate");
if (! validate) {// Form validation failed
return false;
}
// When all the above verifications pass, perform the new operation
$ .messager.confirm ('Warm reminder', 'Whether to confirm the addition', function (r) {
if (r) {
$ .post ("Gift_Add.aspx? method = addGift", $ ("# form"). serialize (), function (data) {
$ .messager.alert ('Success prompt', 'Successfully added', 'info');
});
}
});
});
Summarize:
$.ajax is an AJAX implementation of the traditional get and post methods
$.getjson is JSONP (Remote Data reading) class AJAX implementation
It is called Class Ajax because although he is encapsulated in the JQ Ajax class, it is actually implemented through the script node
The difference between $.getjson and $.ajax in use is:
When sent, $.getjson passes a callback function name (the default is JQ to one)
Receive is, this callback function is called
The server side of the $.getjson must append the passed-in callback function name to the JSON data
Because of this, the returned string is no longer json (the format is wrong)
Therefore there is dataType: the $.ajax of the "JSON" attribute will enter the error branch because of a JSON parsing error