加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在ajax成功中访问javascript变量

发布时间:2020-12-15 22:55:53 所属栏目:百科 来源:网络整理
导读: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函
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`
    )

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读