在ajax成功中访问javascript变量

前端之家收集整理的这篇文章主要介绍了在ajax成功中访问javascript变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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函数中使用它?

任何的想法?

flag和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`
    )

猜你在找的Ajax相关文章