开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜