问题描述:

This question already has an answer here:

  • How do I return the response from an asynchronous call?

    17 answers

网友答案:

Use jQuery.when() for this, which waits for the passed AJAX calls to finish before completing the callback function.

$.validator.addMethod("checkExists",
    function (value, element) {

        var email = $("#email").val();
        var data = {email: email};

        $.when(
            return $.ajax({
                type: "POST",
                url: "http://localhost/CFBserver/check_email.php",
                data: data
            });
        ).done(function(response) {
            return response == 1; // returns true is response is 1, false otherwise
        });
    },
    "This username is already taken! Try another."
    );

I have also simplified your code a bit by returning the boolean value according to the if statement you had.

I would get this AJAX call out of your function and make it a separate one - this way the code will look better and the call can be made from another places.

$.when(checkMail).done(function(response) {
    return response == 1; // returns true is response is 1, false otherwise
});

// Outside of validator function...

function checkMail() {
     return $.ajax({
        type: "POST",
        url: "http://localhost/CFBserver/check_email.php",
        data: data
    });
}

Furthermore, would you also want to handle errors in your AJAX call, use then instead of done and provide two functions as callbacks: one for success, and one for failure:

$.when(checkMail).then(function(response) {
    // Function gets called as 'success' from AJAX
    return response == 1;
}, function (errorResponse) {
    // Function gets called as 'error' from AJAX
    // return false; // or
    // return "Error when checking email: " + errorResponse;
});
相关阅读:
Top