jQuery中调用ajax的4种方法:$.get()、$.post()、$getJSON()和$ajax(),都是异步请求。但有时候不得不用,且需要同步请求时。那我们可参考以下方法
一、$.get()、$.post()和$getJSON()都直接在执行操作之前设置同步即可
//$.post()
$.ajaxSettings.async = false; //执行之前,设置为同步
$.post("url", data, function(result) { });
$.ajaxSettings.async = true; //可选:执行完后,设置回异步
//$.get()
$.ajaxSettings.async = false; //执行之前 设置为同步
$.get("url", data, function(result) { });
//$.getJSON()
$.ajaxSettings.async = false; //执行之前,设置为同步
$.getJSON("url", data, function(result) { });
$.ajaxSettings.async = true; //可选:执行完后,设置回异步
二、$ajax()在请求时可设置“async”参数的值,如下示例
PS:async的默认值是true(异步),当其值为为false时代表同步
$.ajax({
type: "post",
url: "url",
data: {"name":"tom"},
async: false, //同步
success: function(result){
}
});