2011-04-07 60 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

相關問題