Ajax async false is deprecated?

2019-01-28 18:47发布

I am using jQuery 1.7 and I use async:false for my AJAX requets, but I've learned that this function is deprecated.

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:

<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

2条回答
趁早两清
2楼-- · 2019-01-28 19:22

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:

$("#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
        }
    });
});
查看更多
Bombasti
3楼-- · 2019-01-28 19:28

From the documentation:

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated

You are not using it with 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.

查看更多
登录 后发表回答