javascript Ajax async false 已弃用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24187160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ajax async false is deprecated?
提问by user3710381
I am using jQuery 1.7 and I use async:false
for my AJAX requets, but I've learned that this function is deprecated.
我正在使用 jQuery 1.7 并async:false
用于我的 AJAX 请求,但我了解到此功能已被弃用。
I need to use callback but this doesn't work:
我需要使用回调,但这不起作用:
$("#form").submit(function(e) {
var cnf;
$.ajax({
type: "POST",
url: 'page.php',
data: $('#form').serialize(),
async: true,
success: function(responseText) {
if(responseText.indexOf('err') != -1) {
cnf = "error";
}
else {
cnf = "success";
}
return callBack( cnf );
},
error: function() {
cnf = "error";
return callBack( cnf );
}
});
if(cnf == "success")
{
alert('ok');
}
});
The HTML:
HTML:
<form id="form">
<input type="text" name="email">
<input type="submit">
</form>
If I use async: false
this works. Using callBack I see the solution here: wait for a jquery ajax callback from calling function
如果我使用async: false
这个作品。使用 callBack 我在这里看到了解决方案:等待来自调用函数的 jquery ajax 回调
采纳答案by Gone Coding
Continuing from the comments: You seem to be a little obsessed with callbacks, when you don't seem to need any! :)
继续评论:您似乎对回调有点着迷,而您似乎不需要任何回调!:)
The simple change to your existing code is to throw away cnf
and simply put your code in the success part of the ajax call:
对现有代码的简单更改是丢弃cnf
并简单地将代码放在 ajax 调用的成功部分:
$("#form").submit(function (e) {
$.ajax({
type: "POST",
url: 'page.php',
data: $('#form').serialize(),
async: true,
success: function (responseText) {
if (responseText.indexOf('err') != -1) {
// Do something when it fails here
} else {
// Do something when it succeeds here!!!!
alert('ok');
// e.g. move on to "step 2"
}
},
error: function () {
// Do something when it fails here
}
});
});
回答by Quentin
From the documentation:
从文档:
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred)is deprecated
从 jQuery 1.8 开始,不推荐使用带有 jqXHR ($.Deferred)的 async: false
You are not using it with jqXHR
.
您没有将它与jqXHR
.
That said, non-async HTTP is horrible with JavaScript and best avoided. Do your work in or from the callback. Don't try to return data to the calling function so it can do the work.
也就是说,非异步 HTTP 对 JavaScript 来说很糟糕,最好避免。在回调中或从回调中完成您的工作。不要试图将数据返回给调用函数,以便它可以完成工作。