javascript - 成功访问ajax中的javascript变量

标签 javascript jquery ajax

var flag = false; //True if checkbox is checked
$.ajax({
    ... //type, url, beforeSend, I'm not able to access flag here
    success: function(){
        // I'm not able to access flag here
    }
});

在 ajax 内部,如果我尝试访问 flag,它会说它未定义。我如何在 ajax 函数中使用它?

有什么想法吗?

flag 和 ajax 都是函数体。该函数中没有其他内容。

最佳答案

如果您通过引用创建变量,您就可以访问该变量。 Javascript 中的所有对象都是引用值,只是原始值不是(例如:int、string、bool 等...)

所以你可以将你的标志声明为一个对象:

var flag = {}; //use object to endure references.

$.ajax({
    ... //type, url, beforeSend, I'm not able to access flag here
    success: function(){
        console.log(flag) //you should have access
    }
});

或者强制成功函数有你想要的参数:

var flag = true; //True if checkbox is checked

$.ajax({
    ... //type, url, beforeSend, I'm not 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`
});

关于javascript - 成功访问ajax中的javascript变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30734372/

相关文章:

javascript - 使用子组件中的函数更改父状态

javascript - 使用 Javascript 和 JQuery 改变 CSS 属性 : JQuery cannot alter properties that Javascript has already altered?

javascript - 在 Jquery 中选择第一个搜索项而不单击它

javascript - 如果组件的 DOM 元素的宽度发生变化,如何调用函数? ( Angular 4)

javascript - .after() 将第一个 div 作为最后一个

javascript - 使用日期选择器 : simple task

javascript - 用鼠标移动 div 及其内容可点击?

javascript - D3js 与 json 错误

javascript - 将 Javascript 数组发送到 Controller 并在另一个 URL 中渲染 View 结果

javascript - jQuery ajax/post 请求更改页面不起作用