Javascript 实时同步ajax调用
我有一种情况,我不知道我的方法是否正确,但事情是这样的:我希望有第二篇帖子,但前提是第一篇帖子说可以Javascript 实时同步ajax调用,javascript,jquery,ajax,post,synchronization,Javascript,Jquery,Ajax,Post,Synchronization,我有一种情况,我不知道我的方法是否正确,但事情是这样的:我希望有第二篇帖子,但前提是第一篇帖子说可以 function save_match(slot, save) { listItems.each(function(idx, li) { var player = $(li); if(i >= 0) { // do some work } else { // post that shou
function save_match(slot, save) {
listItems.each(function(idx, li) {
var player = $(li);
if(i >= 0) {
// do some work
} else {
// post that should prevent second post from executing, depending on `return_msg`
$.post(..., function(return_msg) {
if(return_msg == "not_ok") {
// I did this in hope that it will do the trick, but no
location.reload();
}
}
);
}
});
// do a little work
$.ajax({
...
});
}
我试图设置一个忙循环,但这会冻结浏览器。我想使第一个POST调用同步(但是,在POST返回之前,它不会让//执行一些工作
,它返回ok
,但我看不到其他替代方法,如果可以的话,请告诉我),这样,如果第一个调用的返回不正常,第二个POST就不会发生
所以,我发现了这个问题:,它说它的首要答案是不推荐的,并且给出了一些会阻止UI的东西。但是,我想阻止代码执行第二个调用
如何在2015年做到这一点?一种方法是使ajax同步,这是不推荐的。您可以在ajax调用中设置
async:false
另一种方法是将一个ajax请求放入另一个ajax请求的成功回调中。一个简单的例子是:
$.ajax({
url: "ajaxUrl",
type: "post",
success: function (data) {
if (data == "OK") {
//do other ajax
}
else {
}
},
error: function (jqxhr) { }
});
对于您的情况,上面的示例可能就足够了。您可以使用更健壮、更可扩展的解决方案。下面是一个简单的例子:
var def = $.Deferred(); //Create $.Deferred;
$.ajax({
url: "ajaxUrl",
type: "post",
success: function (data) {
if (data == "OK")
def.resolve(); //Let deferred know it was resolved with success
else
def.reject(); //Let deferred know it ended in a failure
},
error: function (jqxhr) { }
});
def.done(function () {
//this will only run when deferred is resolved
}).fail(function(){
//this will only run when deferred is rejected
}).always(function(){
//this will run when deferred is either resolved or rejected
})
当return\u msg
不等于NOT\u ok
时,您正在发出“Error!”警报。如果消息是ok
或not_ok
,那就是你想要第二篇文章的地方,而且你似乎已经知道如何发帖了
$.post(..., function(return_msg) {
// check for the success, as null or something else would be an error too
if(return_msg == "ok") {
// This is where you would do another post
$.post(..., function() {});
} else {
// This is where the error should be.
}
}
);
当
return\u msg
不等于NOT\u ok
时,您正在发出“Error!”警报。如果消息是ok
或not_ok
,则您需要第二篇文章,而且您似乎已经知道如何发布。@popleak,代码变小后的剩余内容,谢谢!您可以使用异步技术使第二个请求等待第一个请求,而无需暂停浏览器UI来执行此操作。async:false
是我问题的答案中提到的!!!def
方法看起来不错。你能描述一下什么是jQuery.Deferred吗?虽然我了解它的功能,但文档中并不清楚。我担心它的复杂性(例如,它会使我的应用程序更重吗?)。我明天再来看看!有大量关于jQuery.Deferred的文档。谷歌和jQuery网站比我在这里能给你们的帮助更多。正如我所说,对于您的情况,第一个示例为您提供了一个简单的解决方案。仅当第一个返回OK时才执行第二个ajax。