문제

I have a fairly simple task to replace specif texts on a page. Say, there are 10 DIVs, each of which containing a specific information. I want to check this information against a database, and replace the text with a result from the database.

I place GM_xmlhttpRequest inside a loop that should check this information and replace it for each of the 10 DIVs. Unfortunately, this doesn't work and the last DIV contains 10 very same information. In other words, GM_xmlhttpRequest is executed 10 times when i=10.

Below is a simplified code:

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++;
)
도움이 되었습니까?

해결책

Ajax is asyncronous, so when response will be delivered, your loop will be already ended (so i=11).

But you can use closure for handling 'i' in response function:

 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++;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top