2

페이지의 특정 텍스트를 대체하는 작업이 매우 간단합니다. 예를 들어 10 개의 DIV가 있으며 각 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

아약스가 asyncronous, 그래서 응답이 전달 될 때, 루프는 이미 (너무 i=11) 종료됩니다.

하지만 당신은 응답 기능에 '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

@meeteresteded 당신을 진심으로 환영합니다. 나는 너를 도울 수있어서 기뻐. – Engineer