在ajax成功内访问javascript变量 [英] Access javascript variable inside ajax success

查看:73
本文介绍了在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内,如果我尝试访问flag,则表示未定义.我如何在Ajax函数中使用它?

Inside ajax, if i try to access flag it says it is not defined. How do i use it inside ajax function?

有什么想法吗?

标志和ajax都是函数的主体.该函数内部没有其他内容.

Both flag and ajax is body of a function. Nothing else is present inside that function.

推荐答案

如果通过引用将变量赋值,则可以访问该变量. Javascript中的所有对象都是引用值,而本地值不是(例如int,string,bool等)

You got acces to the variable if you make it by reference. All objects in Javascript are references values, just the native values aren't ( such as; int, string, bool, etc ... )

因此,您可以将标志声明为对象:

So you can either declare your flag as an object:

    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
        }
    )

或强制成功函数具有所需的参数:

Or force the success function to have the parameters you want:

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

这篇关于在ajax成功内访问javascript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆