jQuery: $.ajax success callback doesn't let me assign to outside private variable [duplicate]

≡放荡痞女 提交于 2019-12-12 13:28:37

问题


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.



来源:https://stackoverflow.com/questions/9400465/jquery-ajax-success-callback-doesnt-let-me-assign-to-outside-private-variabl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!