真正的同步ajax调用
Real synchronous ajax call
我有一种情况,我不知道我是否接近正确,但这里是这样的:我想要第二个POST发生,但只有当第一个POST说OK。
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调用同步(但是不会让//do some work
执行,直到POST返回,其中93%返回ok
,但我看不到另一个替代方案,如果可以,请让我知道),因此,如果第一个调用的返回不正确,第二个POST将不会发生。
所以,我发现了这个问题:如何使jquery"$。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) { }
});
对于您的情况,上面的例子可能已经足够了。对于更健壮和可伸缩的解决方案,您可以使用jQuery.Deferred。一个简单的例子:
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_msg
不等于not_ok
时,您正在警告"错误!"如果消息是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.
}
}
);
相关文章:
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- Javascript/jQuery中的并行Ajax调用
- 任何方式使AJAX调用Gmail API,而无需通过JS库
- node.js请求数据事件未在CORS ajax调用中触发
- 如何从ajax调用返回.wrap()元素
- Ajax调用在Firefox中不会自动响应
- AJAX调用中的非法调用
- 使用AJAX调用将GeoJSON数据拉入传单
- 在MVC 4中,对Controller的Ajax调用为空
- Jquery:对返回JSON数据的php脚本的Ajax调用
- 在ajax调用中阻止来自JS对象的函数
- 如何在MVC5中ajax调用的部分视图中引用外部javascript
- 页面加载后的Ajax调用
- 如何使用Ajax调用特定的控制器和操作来重定向用户
- curl和fileget_contents在ajax调用后不起作用
- 在任何AJAX调用之前触发一个javascript函数
- 无法在mvc视图中使用ajax调用获取操作返回的模型对象列表
- Ajax调用ERror Cross Origin REquest:在rails中自动完成大学列表
- ASP.NET MVC 3-在ajax调用后,重定向到新页面或生成页面刷新
- 点击功能没有'ajax调用动态元素(Backbone)后无法工作