var doCheck = function() {
var data;
$.ajax({
url: 'check.php',
data: 'ch=check',
success: function(resp) {
data = resp;
}
});
console.log(data);
return data == 1;
};
以上code,不管数据永远只能返回 0
或 1
。内的成功的回调的范围,这是事实。参数 RESP
的 0
或 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
.
不过,每当我尝试访问私有变量(应该不会受到影响范围),没有任何反应;当的console.log(数据);
被称为所有写入控制台
是未定义
。
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.
阿贾克斯是异步的。这就是为什么你要组织你的逻辑和回调:
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
});