简体   繁体   English

不建议使用Ajax异步false?

[英]Ajax async false is deprecated?

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,并且为我的AJAX报告使用了async:false ,但是我了解到此功能已被弃用。

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. 如果我使用async: false则可以使用。 Using callBack I see the solution here: wait for a jquery ajax callback from calling function 使用callBack我在这里看到解决方案: 等待来自调用函数的jquery ajax回调

From the documentation: 从文档中:

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated 从jQuery 1.8开始,不建议将async:false 与jqXHR($ .Deferred)一起使用

You are not using it with jqXHR . 您没有将其与jqXHR一起jqXHR

That said, non-async HTTP is horrible with JavaScript and best avoided. 也就是说,非异步HTTP对于JavaScript来说是可怕的,最好避免。 Do your work in or from the callback. 在回调中执行您的工作。 Don't try to return data to the calling function so it can do the work. 不要试图将数据返回给调用函数,这样它就可以完成工作。

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
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM