问题描述
ajax嵌套,beforeSend中对页面的渲染方法没有生效
$.ajax({
type:'post',
url:api['selectChina'],
xhrFields:{withCredentials:true},
data: result,
beforeSend:function(){disbtn(btn);},
success:function(json){
$.ajax({
type:'post',
url:api['save'],
xhrFields:{withCredentials:true},
data: result,
beforeSend:function(){disbtn(btn);},
success:function(json){
...
},
complete:function(){undisbtn(btn,str);},
error:function(){showmsg('提交失败,请稍后再试。','0');}
})
},
complete:function(){undisbtn(btn,str);},
error:function(){showmsg('提交失败,请稍后再试。','0');}
})
原因
内外都是异步的请求,导致beforeSend渲染后,又被complete渲染回来了;
改一
将内外都改成同步请求 , 还是不生效
$.ajax({
type:'post',
url:api['selectChina'],
xhrFields:{withCredentials:true},
data: result,
async:false,
beforeSend:function(){disbtn(btn);},
success:function(json){
$.ajax({
type:'post',
url:api['save'],
xhrFields:{withCredentials:true},
data: result,
async:false,
beforeSend:function(){disbtn(btn);},
success:function(json){
...
},
complete:function(){undisbtn(btn,str);},
error:function(){showmsg('提交失败,请稍后再试。','0');}
})
},
complete:function(){undisbtn(btn,str);},
error:function(){showmsg('提交失败,请稍后再试。','0');}
})
原因
再往上查了一下 有说是因为 这个原因就是ajax的async设置为false时同步提交。浏览器的渲染(UI)线程和js线程是互斥的,在执行js耗时操作时,页面渲染会被阻塞掉。
改二
$.ajax({
type:'post',
url:api['selectChina'],
xhrFields:{withCredentials:true},
data: result,
beforeSend:function(){disbtn(btn);},
success:function(json){
$.ajax({
type:'post',
url:api['save'],
xhrFields:{withCredentials:true},
data: result,
async:false,
beforeSend:function(){disbtn(btn);},
success:function(json){
...
},
complete:function(){undisbtn(btn,str);},
error:function(){showmsg('提交失败,请稍后再试。','0');}
})
},
complete:function(){undisbtn(btn,str);},
error:function(){showmsg('提交失败,请稍后再试。','0');}
})
我将外面的改成异步的,内层保持同步,保证我的渲染效果.