Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jquery - Access javascript variable inside ajax success

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

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

Any Idea?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have access to the variable if you make it by reference. All objects in Javascript are referenced values, just the primitive 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'm not 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'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`
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...