Jquery 等待多个Ajax Webmethod,以执行重定向
我有一大堆东西要插入购物车,我用Ajax调用了N次WebMethod。当我完成插入它们时,我需要重定向到摘要页面Jquery 等待多个Ajax Webmethod,以执行重定向,jquery,asp.net,ajax,webmethod,Jquery,Asp.net,Ajax,Webmethod,我有一大堆东西要插入购物车,我用Ajax调用了N次WebMethod。当我完成插入它们时,我需要重定向到摘要页面 function SellAll(){ $.each(x,function (index, value) { $.ajax({ type: "POST", url: "find.aspx/AddItem", data: "{'id': '" + value + "'}"
function SellAll(){
$.each(x,function (index, value) {
$.ajax({
type: "POST",
url: "find.aspx/AddItem",
data: "{'id': '" + value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "false",
success: function (response) {
...
}
});
})
document.location.href = "summary.aspx";
};
如果我调用函数SellAll,summary页面是空的,但是如果我删除重定向并执行该函数,然后手动进入summary页面,我会找到包含项目的购物车
如何修复此错误
谢谢 Move document.location.href=summary.aspx;从它的当前位置,它可能是这样的:
$.when(SellAll()).done(function(a1, a2, a3, a4){
// the code here will be executed when all four ajax requests resolve.
// a1, a2, a3 and a4 are lists of length 3 containing the response text,
// status, and jqXHR object for each of the four ajax calls respectively.
document.location.href = "summary.aspx";
});
我不知道这是如何工作的,因为您多次调用SellAll本身,我感觉jQuery可能希望在每次完成时触发
如果这是您的问题,那么您可以设置一些逻辑来为每个请求创建变量,并将这些变量传递给$.when函数
例如:
var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();
$.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) {
console.log( v1 ); // v1 is undefined
console.log( v2 ); // v2 is "abc"
console.log( v3 ); // v3 is an array [ 1, 2, 3, 4, 5 ]
});
d1.resolve();
d2.resolve( "abc" );
d3.resolve( 1, 2, 3, 4, 5 );`
其中d1、d2和d3将是您正在排队的ajax请求。看看这个答案。thx男士:这很好,我用这个解决了这个问题:哈哈,我看到了这个答案,我想这个可能对您更合适。我担心每次ajax请求完成时,另一个问题会再次出现。