var flag = false; //True if checkbox is checked
$.ajax({
... //type, url, beforeSend, I'm not able to access flag here
success: function(){
// I'm not able to access flag here
}
});
在 ajax 内部,如果我尝试访问 flag
,它会说它未定义。我如何在 ajax 函数中使用它?
有什么想法吗?
flag 和 ajax 都是函数体。该函数中没有其他内容。
最佳答案
如果您通过引用创建变量,您就可以访问该变量。 Javascript 中的所有对象都是引用值,只是原始值不是(例如:int、string、bool 等...)
所以你可以将你的标志声明为一个对象:
var flag = {}; //use object to endure references.
$.ajax({
... //type, url, beforeSend, I'm not able to access flag here
success: function(){
console.log(flag) //you should have access
}
});
或者强制成功函数有你想要的参数:
var flag = true; //True if checkbox is checked
$.ajax({
... //type, url, beforeSend, I'm not able to access flag here
success: function(flag){
console.log(flag) //you should have access
}.bind(this, flag) // Bind set first the function scope, and then the parameters. So success function will set to it's parameter array, `flag`
});
关于javascript - 成功访问ajax中的javascript变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30734372/