Ajax請(qǐng)求中的async:false/true的作用
官方的解釋是:http://api.jquery.com/jQuery.ajax/
async Boolean Default: true
By default, all requests are sent asynchronous (e.g. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
async. 默認(rèn)是true,即為異步方式,.Ajax里的success方法,這時(shí)候執(zhí)行的是兩個(gè)線(xiàn)程趁餐。若要將其設(shè)置為false喷兼,則所有的請(qǐng)求均為同步請(qǐng)求,在沒(méi)有返回值之前后雷,同步請(qǐng)求將鎖住瀏覽器季惯,用戶(hù)其它操作必須等待請(qǐng)求完成才可以執(zhí)行。
下面查看一個(gè)示例:
var temp;
$.ajax({
async: false,
type : "POST",
url : defaultPostData.url,
dataType : 'json',
success : function(data)
{
temp=data;
}
});
alert(temp);
這個(gè)ajax請(qǐng)求為同步請(qǐng)求臀突,在沒(méi)有返回值之前勉抓,alert(temp)是不會(huì)執(zhí)行的。
如果async設(shè)置為:true惧辈,則不會(huì)等待ajax請(qǐng)求返回的結(jié)果琳状,會(huì)直接執(zhí)行ajax后面的語(yǔ)句。
不過(guò)上面設(shè)置同步請(qǐng)求的方法盒齿,有網(wǎng)友曾經(jīng)反饋將async設(shè)成false后, 原意是想返回?cái)?shù)據(jù)了再執(zhí)行$.Ajax后面的腳本, 沒(méi)想到這個(gè)地方卻導(dǎo)致了在火狐瀏覽器下出現(xiàn)閃屏(Firefox 11.0),滾動(dòng)條下拉到底部觸發(fā)ajax的情況困食。最后只能將async:false注釋掉边翁, 也就是async為ture的情況下,成功解決了火狐瀏覽器滾動(dòng)條下拉到底部觸發(fā)ajax出現(xiàn)閃屏的問(wèn)題硕盹。
轉(zhuǎn)載出處:http://www.penglig.com/post-172.html