How to access a variable state from before an ajax request in the call back function
EG
for(i in an_object){
$.getJSON("http//www...." + "?callback=?",'', function(data){
// do something using what the value of i from when the JSONP request was sent
// but i is always the l开发者_StackOverflow社区ast value in an_object because the loop
// has finished by the time the callback runs.
);
});
}
If you only need one variable, you can bind it as context to the function using proxy:
var state=1, callbackfunction = function(data) {
if (this===1) {
//something based on state
}
}
$.getJSON("http//www..",'', jQuery.proxy( callbackfunction , state) );
I solved this by putting the ajax call inside an anonymous function. eg:
for(i in an_object){
(function(i){
$.getJSON("http//www...." + "?callback=?",'', function(data){
// i now remembers its state.
});
})(i);
}
精彩评论