【问题标题】:JS/Ajax/Jquery consecutive requests through linked list [duplicate]JS / Ajax / Jquery通过链表连续请求[重复]
【发布时间】:2021-07-16 17:39:32
【问题描述】:

我的代码:

<script type="text/javascript">
    var x = 1;
    var data  = JSON.parse( document.getElementById('json').innerHTML);
    var next = data['next'];
    var jsonData = data['data'];
    
    while (next != null) {
      x = x+1;
      var nextFileUrl = data['next'];
      console.log('next:', nextFileUrl);
      
      const xhr = new XMLHttpRequest();
      xhr.addEventListener("readystatechange", function () {
        if (this.readyState === this.DONE) {
          data = this.response;
          next = JSON.parse(this.response)['next'];
          console.log('newNext:',next);
          newJsonData = JSON.parse(this.response)['data'];
          console.log('newJsonData:',newJsonData);
          jsonData['data'].push(newJsonData);
        }
      });
      xhr.open("GET", nextFileUrl);
      xhr.send(null);  
                
    }
  </script>

数据示例:

{
"next" : "path2",
"data" : "some data here"
}

我有多个如上所述的 JSON 文件,我需要在“while next != null”类型的循环中连续访问这些文件,从页面中已有的数据开始。对于每次调用,我都需要获取数据值,并对其进行处理,然后进行下一次调用。目前,我的代码似乎一直只记录第一个响应的结果。

我对 javascript 和 ajax 还很陌生,并且没有使用 jquery 的经验。我不能使用 fetch,因为我需要适用于所有浏览器的解决方案。如果有人能指出正确的方向,我正在寻找 JS、Ajax 和 JQuery 之间的最佳解决方案。

【问题讨论】:

    标签: javascript jquery ajax loops while-loop


    【解决方案1】:

    您在 while 循环中发送异步请求并期望更新每次迭代的值,但这永远不会起作用,因为循环不会等待请求完成。您可以递归调用函数,而不是循环,直到满足条件

    var x = 1;
    var data = JSON.parse(document.getElementById('json').innerHTML);
    var next = data['next'];
    var jsonData = data['data'];
    
    function cycle() {
      if (!next) return;
      x = x + 1;
      var nextFileUrl = next;
      console.log('next:', nextFileUrl);
    
      const xhr = new XMLHttpRequest();
      xhr.addEventListener("readystatechange", function() {
        if (this.readyState === this.DONE) {
          data = this.response;
          next = JSON.parse(this.response)['next'];
          console.log('newNext:', next);
          newJsonData = JSON.parse(this.response)['data'];
          console.log('newJsonData:', newJsonData);
          jsonData['data'].push(newJsonData);
    
          // call the function 
          if (next) cycle();
        }
      });
      xhr.open("GET", nextFileUrl);
      xhr.send(null);
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-10
      • 1970-01-01
      • 2017-03-13
      相关资源
      最近更新 更多