【问题标题】:GM_xmlhttpRequest inside WHILE loop [duplicate]WHILE 循环中的 GM_xmlhttpRequest [重复]
【发布时间】:2012-04-27 00:17:09
【问题描述】:

我有一个相当简单的任务来替换页面上的特定文本。假设有 10 个 DIV,每个 DIV 都包含特定信息。我想对照数据库检查这些信息,然后用数据库中的结果替换文本。

我将 GM_xmlhttpRequest 放在一个循环中,该循环应该检查此信息并为 10 个 DIV 中的每一个替换它。不幸的是,这不起作用,最后一个 DIV 包含 10 个完全相同的信息。也就是说,当 i=10 时,GM_xmlhttpRequest 被执行了 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++;
)

【问题讨论】:

    标签: javascript while-loop greasemonkey fetch gm-xmlhttprequest


    【解决方案1】:

    Ajax 是异步的,所以当响应被传递时,你的循环已经结束(所以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++;
    }
    

    【讨论】:

    • 完美,现在可以使用了。非常感谢!
    • @mrinterested 不客气。很高兴能为您提供帮助。
    猜你喜欢
    • 2015-10-26
    • 2014-03-23
    • 2013-05-21
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    相关资源
    最近更新 更多