我在我的javascript函数中发布了一堆延迟的'then's。
在JQuery 1.7.2中,我可以创建类似于以下示例的东西,通过传递每个参数来确定是否继续。
myAjaxFunction(myParametersObject)
.done(function (noErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (noErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (noErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (noErrors) {
if (anyErrors == true) {
// final code here
}
});
它在JQuery 1.7.2上工作完美,但我正在做一个需要JQuery 1.11.1的项目,这不再工作。
如何在JQuery 1.11.1中传递参数到即将到来的'then' ?
在done
处理程序参数参数
myAjaxFunction
返回的jQuery承诺值似乎被定义为noErrors
.done(function (noErrors) {
在.done
处理程序作为anyErrors
?
if (anyErrors == true) {
类似于
.then(function (noErrors) {
if (anyErrors == true) {
// call ajax routine
?
尝试在处理程序中设置与参数参数相同的参数,例如。anyErrors
var dfd = $.Deferred().resolve(true);
dfd.done(function (anyErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (anyErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (anyErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (anyErrors) {
if (anyErrors == true) {
// final code here
document.body.textContent = anyErrors;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
jsfiddle http://jsfiddle.net/zr5rzb7v/1/
如果您使用first then然后done,则可以使用它:
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
查看官方jquery api文档:http://api.jquery.com/deferred.then/#deferred-then-doneFilter-failFilter-progressFilter