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 } );
在ajax内部,如果我尝试访问标志,它说它没有定义.我如何在ajax函数中使用它?
任何的想法?
解决方法
如果通过引用创建变量,则可以访问该变量. Javascript中的所有对象都是引用值,只是原生值不是(例如; int,string,bool等…)
因此,您可以将标志声明为对象:
var flag = {}; //use object to endure references. $.ajax( ... //type,I cannot able to access flag here success: function() { console.log(flag) //you should have access } )
或者强制成功函数获得所需的参数:
var flag = true; //True if checkBox is checked $.ajax( ... //type,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` )