2011-04-07 59 views
0

EG如何从一个Ajax请求之前访问变量状态回调函数

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 last value in an_object because the loop 
       // has finished by the time the callback runs. 
      ); 
     }); 
} 
+0

看到可能的重复 - http://stackoverflow.com/questions/tagged/javascript+closures+loops – Anurag 2011-04-07 07:52:12

回答

0

我通过将ajax调用放入匿名函数中解决了这个问题。例如:

for(i in an_object){ 

    (function(i){ 

     $.getJSON("http//www...." + "?callback=?",'', function(data){ 
       // i now remembers its state. 
     }); 
    })(i); 
} 
0

如果你只需要一个变量,你可以使用代理绑定它作为背景的功能:

var state=1, callbackfunction = function(data) { 
    if (this===1) { 
    //something based on state 
    } 
} 

$.getJSON("http//www..",'', jQuery.proxy(callbackfunction , state)); 
+0

感谢您的输入,但我发现了一个更好的解决方案,它接受任意数量的参数 - 见我回答。 – SystemicPlural 2011-04-07 13:28:03

相关问题