我想实现多个 ajax post 请求。假设有 3 个帖子。然后第二个帖子依赖于第一个帖子的结果,第三个帖子依赖于从第二个帖子收到的结果。
如何放置第二个 ajax post 方法。应该在成功处理程序中完成吗 jQuery.ajax({ 类型:“发布”, 数据类型:“json”, 网址:ajaxurl, 数据:表单数据,
async: false,
success: function(response) {
//2nd ajax post call to be placed here?
}
}
})
//或者应该在
之后放置第二个 ajax post 调用我看到有些人也在使用 jQuery.when() 但我不确定我是否可以使用它。 从这里开始,我将不得不检查 when 条件 3 次。
提前致谢。
最佳答案
是这样的吗?
来自 https://api.jquery.com/jQuery.when/
$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
// Each argument is an array with the following structure: [ data, statusText, jqXHR ]
var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"
if ( /Whip It/.test( data ) ) {
alert( "We got what we came for!" );
}
});
a1,a2 是各种回调返回的结果? (然而,这将执行您的三个回调(异步),但返回所有三个的结果)
否则,如果你有从 request1 到 request2 的依赖关系,你可以这样做 https://api.jquery.com/jQuery.ajax/
$.ajax("page1.php").done(function(a1) {
if (a1 == "something") { // if 2nd call dependent on results from 1st
$.ajax("page2.php").done(function(a2) {
}).fail(function() {
// handle with grace
});
}
}).fail(function() {
// handle with grace
});
关于javascript - 以串行方式发布多个 Ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22141247/