我正在使用jquery ajax api调用web方法,并在success
上实现一个类似showHideDomElement
的功能。
function showHideDomElement(data)
{
if(data == 1 )
$('#selector').show();
else
$('#selector').hide();
}
这就是我所说的
function Validatebatch() {
$.ajax({
type: "POST",
url: getControllerURL("/Invoice") + "/ValidateBatch",
data: {
"Id": $('#someselector').val()
},
async: true, // i tried with 'false' but it affect performance
dataType: "json",
success: function(data) {
showHideDomElement(data);
}
});
}
对Validatebatch
函数的ajax请求被多次引发,因此有多个活动的http请求指向url
在不同的时间完成。
由于异步行为,success callback
可以按不同的顺序执行。
完成的顺序是产生问题的原因。请建议一种方法来绑定ajax请求,使其按照执行的顺序运行/完成(请建议使用jquery async
属性以外的属性)
谢谢
发布于 2015-12-07 14:58:23
首先,您必须重写Validatebatch函数,以便它返回由$.ajax调用生成的Promise,例如:
function Validatebatch() {
return $.ajax({
然后,您必须存储每个Validatebatch调用的promise,并仅在前一次调用完成后才使用它来触发下一次Validatebatch,您应该具有如下内容:
promise = Validatebatch(); // call Validatebatch the first time and store the returned Promise object
promise = promise.then(Validatebatch); // another call to Validatebatch, only triggered after the previous has ended
promise = promise.then(Validatebatch); // again, this third Validatebatch call will only happen after the second one has ended.
https://stackoverflow.com/questions/34135089
复制