jquery ajax异步和同步从后天取值

时间:2023-03-08 17:15:21

最近使用jquery的ajax,发现有些效果不对,ajax请求后返回的json串回来了,但是执行顺序有问题。

var isReload = false;

$.post('/home/DetectCachedLoginInfor/',

function (result) {
if (result.errorMsg) { if (result.errorMsg) { alert(result.errorMsg); isReload = true; }
}
}, 'json'); if (isReload)
{
OpenReloginForm();
return false;
}

发现得到返回数result.errorMsg了,但是isReload 不能给赋值为true,下面的if (isReload){...}不能被顺利执行

最后发现是post的异步执行顺序问题,所以研究了下,写了以下总结

--------因为post默认为异步请求,数据是异步返回的不是顺序执行一直到数据返回才执行下一步。

所以我们更换取值的方法,ajax--async: false 即可

var isReload = false;

$.ajax({
url: '/home/DetectCachedLoginInfor/',
async: false, // 注意此处需要同步,因为返回完数据后,下面才能让结果的第一条selected
type: "POST",
dataType: "json",
success: function (result) {
if (result.errorMsg) { alert(result.errorMsg); isReload = true; }
}
}); if (isReload)
{
OpenReloginForm();
return false;
}