javascript - WHILE 循环内的 GM_xmlhttpRequest

标签 javascript while-loop greasemonkey fetch gm-xmlhttprequest

我有一个相当简单的任务来替换页面上的特定文本。假设有 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++;
)

最佳答案

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++;
}

关于javascript - WHILE 循环内的 GM_xmlhttpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10161063/

相关文章:

javascript - 如何/在何处将数据存储在 localStorage 以外的 Chrome Tampermonkey 脚本中?

javascript - 如何使用 Greasemonkey/Tampermonkey 脚本更改类 CSS?

javascript - Ajax:在没有回显的情况下将 PHP 变量发送到 JS?

javascript - 光标远离javascript图表的工具提示

Python while 循环没有按预期工作

python - Python 中的并行 while 循环

javascript - 如何使用 Bootstrap 正确设置按下按钮时显示的模式?

javascript - 如何使用reactjs获取整个数据 block ?

regex - 带正则表达式的选择字符串,并拆分/输出到多个文件

javascript - 可以改进此代码以避免内存泄漏或更稳定吗?