jQuery: $.ajax success callback doesn't let me

2019-07-04 23:41发布

问题:

This question already has an answer here:

  • How do I return the response from an asynchronous call? 35 answers
var doCheck = function() {
    var data;

    $.ajax({
        url: 'check.php',
        data: 'ch=check',
        success: function(resp) {
            data = resp;
        }
    });
console.log(data);
    return data == 1;
};

The above code, regardless of the data only ever returns a 0 or a 1. Within the scope of the success callback, this is true. The argument resp has a value of 0 or 1 depending on input.

However, whenever I try to access a private variable (should not be affected by scope), nothing happens; and when console.log(data); is called all that is written to the console is undefined.

This function has no parent, so don't worry about some other kind of scope interference.

回答1:

Ajax is asynchronous. Which is why you have to organize your logic with callbacks:

var doCheck = function(callback) {
    var data;

    $.ajax({
        url: 'check.php',
        data: 'ch=check',
        success: function(resp) {
            callback(data == 1);
        }
    });
};

doCheck(function(result) {
    // result is true or false
});


回答2:

Place the 'console.log(data)' sentence after 'data=resp'. Probably it is executing before the success method and becuase this it has no value set.



回答3:

It takes time till you get the response, so the console.log() comes when the data isn't set yet



回答4:

This is because the ajax Request by default is asynchronous, however instead of making it synchronous, I'd suggest redesigning you're approach.



回答5:

Ajax stands for Asynchronous JavaScript and XML. data is being set after the call to the server returns, and only if the call was sucessfull.

The console.log is happening immediatly after sending the async request off, before the sucess has a chance to run.