2012-04-15 20 views
2

私はページ上の特定のテキストを置き換えるのにかなり簡単な作業があります。つまり、10個のDIVがあり、それぞれに固有の情報が含まれています。この情報をデータベースと照合し、テキストをデータベースの結果と置き換えたいとします。WHILEループ内のGM_xmlhttpRequest

GM_xmlhttpRequestをループ内に配置し、この情報をチェックして、10個のDIVのそれぞれについて置き換える必要があります。残念ながら、これは機能しません。最後のDIVには10個の非常に同じ情報が含まれています。つまり、GM_xmlhttpRequestは、i = 10のときに10回実行されます。

以下

単純化されたコードです:

var i=1; 
while (i<=10) { 
    var id = 'div-' + i; //This sets the name of the DIV 
    var ShowContent = document.getElementById(id); 
    GoToURL = "http://domain.com/?=" + id; //This specifies a URL that changes on every loop 
    GM_xmlhttpRequest({ 
    method: "GET", 
    url: GoToURL, 
    onload: function(response) { 
     ShowContent.innerHTML = response; //This should replace the information for each DIV 
     alert(i); //TEST: this shows always 11 (even not 10!). Why? 
    } 
    }); 
    i++; 
) 

答えて

3

(そうi=11)アヤックスasyncronousので、応答が配信されます場合は、あなたのループはすでに終了します。

しかし、あなたは応答関数で'i'を処理するためのクロージャを使用することができます。

var i=1; 
while (i<=10) { 
    (function(i){ 
    var id = 'div-' + i; //This sets the name of the DIV 
    var ShowContent = document.getElementById(id); 
    GoToURL = "http://domain.com/?=" + id; //This specifies a URL  
    GM_xmlhttpRequest({ 
     method: "GET", 
     url: GoToURL, 
     onload: function(response) { 
      ShowContent.innerHTML = response; //This should replace the information for each DIV 
      alert(i); 
     } 
    }); 
    })(i); 
    i++; 
} 
+0

パーフェクト、それが機能するようになりました。どうもありがとうございました! – mrinterested

+0

@minterestedあなたは大歓迎です。私はあなたを助けることができてうれしいです。 – Engineer