jQuery Ajax async=false异步改为同步时,解决导致浏览器假死的问题

2020-05-23 06:16:43易采站长站整理

$("#flushbutton").replaceWith('<a style="color:#3fb0ff;font-size:14px;" href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="flushbutton">正在刷新</a>');
setTimeout(function(){
$.ajax({
url:'URL',
type:'post',
async:false,
// data:{},
success:function(json){
json = eval('('+json+')');
if(json.url){window.location.href=json.url;return;}
$("#flushbutton").replaceWith('<a style="color:#3fb0ff;font-size:14px;" href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="flushFreeSum();" id="flushbutton">刷新积分</a>');
if(json.code!=1){
alert(json.msg);
}else{
$("#free_sum").html(json.free_sum);
}
return;
}
});
},0)
}

setTimeout的第二个参数设为0,浏览器会在一个已设的最小时间后执行

到这里问题就解决了,但是你可以试试当你点击按钮的时候如果需要弹出一个gif图片,并且图片一直在旋转,提示更新中,你会发现图片虽然会显示,但是图片却是不动的,那是因为虽然同步请求延迟执行了,但是它执行期间还是会把UI线程给阻塞。这个阻塞相当牛逼,连gif图片都不动了,看起来像一张静态图片一样。结论很明显,setTimeout治标不治本,相当于把同步请求“稍稍”异步了一下,接下来还是会进入同步的噩梦,阻塞线程,这种方法只适合发请求之前操作简单的时间短的情况

2.使用 Deferred 来解决

jQuery在1.5版本之后,引入了Deferred对象,提供的很方便的广义异步机制。


function getData3(){ var defer = $.Deferred();
$.ajax({
url : 'p.php', //async : false,
success: function(data){
defer.resolve(data)
}
}); return defer.promise();
}
$('.btn3').click(function(){
$('.loadingicon').show();
$.when(getData3()).done(function(data){
$('.loadingicon').hide();
alert(data);
});
});

可以看到我在ajax请求中去掉了async:false,也就是说,这个请求又是异步的了。另外请注意success函数中的这一句:defer.resolve(data),Deferred对象的resolve方法可传入一个参数,任意类型。这个参数可以在done方法中拿到,所以我们异步请求来的数据就可以以这样的方式来返回了。

至此,问题得到了解决。Deferred对象如此强大且方便,我们可以好好利用它。


<button class="btn1">async:false</button><button class="btn2">setTimeout</button><button class="btn3">deferred</button>
<img class="loadingicon" style="position:fixed;left:50%;top:50%;margin-left:-16px;margin-top:-16px;display:none;" src="loading2.gif" alt="正在加载" /><script>