Gib*_*bbs 9 javascript ajax jquery
var flag = false; //True if checkbox is checked
$.ajax(
... //type,url,beforeSend, I cannot able to access flag here
success: function()
{
//I cannot able to access flag here
}
);
Run Code Online (Sandbox Code Playgroud)
在ajax内部,如果我尝试访问flag它,说它没有定义.我如何在ajax函数中使用它?
任何的想法?
flag和ajax都是函数体.该功能内不存在任何其他内容.
如果您通过引用将其访问,则可以访问该变量。Javascript中的所有对象都是引用值,而本地值不是(例如int,string,bool等)
因此,您可以将标志声明为对象:
var flag = {}; //use object to endure references.
$.ajax(
... //type,url,beforeSend, I cannot able to access flag here
success: function()
{
console.log(flag) //you should have access
}
)
Run Code Online (Sandbox Code Playgroud)
或强制成功函数具有所需的参数:
var flag = true; //True if checkbox is checked
$.ajax(
... //type,url,beforeSend, I cannot 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`
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12667 次 |
| 最近记录: |