【问题标题】:API with Query Params带有查询参数的 API
【发布时间】:2018-09-13 04:32:44
【问题描述】:

当我运行下面的代码时,我没有收到错误的 URL 列表

$(document).ready(function($) {


 const app = document.getElementById('theTable');

 const container = document.createElement('div');
 container.setAttribute('class', 'container');


 app.appendChild(container);

 var request = new XMLHttpRequest();
 var theMainAPI = '/Aud/1234/run/123456/result/pages/'
 request.open('GET', theMainAPI, true);
 request.onload = function () {

var x = document.createElement("TABLE");
x.setAttribute("id", "myTable");
document.body.appendChild(x);

// Begin accessing JSON data here
   var data = JSON.parse(this.response);
   if (request.status >= 200 && request.status < 400) {
      data.forEach(theUrls => {
      var y = document.createElement("TR");
      y.setAttribute("id", "myTr");
      document.getElementById("myTable").appendChild(y);
      var z = document.createElement("TD");
      var t = document.createTextNode(theUrls);
      z.appendChild(t);
      document.getElementById("myTable").appendChild(z);
   });
   } else {
     const errorMessage = document.createElement('marquee');
     errorMessage.textContent = `Gah, it's not working!`;
     app.appendChild(errorMessage);
   }
}

request.send();
});

我想使用这些 URL 作为查询参数来生成一组新的 API 并从中获取值。

例如:

$(document).ready(function($) {


 const app = document.getElementById('theTable');

 const container = document.createElement('div');
 container.setAttribute('class', 'container');


 app.appendChild(container);

 var request = new XMLHttpRequest();
 var theMainAPI = '/Aud/1234/run/123456/result/pages/page?url=https%3A%2F%2Fwww.abc.com%2Fat-work%2F'
 request.open('GET', theMainAPI, true);
 request.onload = function () {

var x = document.createElement("TABLE");
x.setAttribute("id", "myTable");
document.body.appendChild(x);

// Begin accessing JSON data here
   var data = JSON.parse(this.response);
   if (request.status >= 200 && request.status < 400) {
      data.forEach(theUrls => {
      var y = document.createElement("TR");
      y.setAttribute("id", "myTr");
      document.getElementById("myTable").appendChild(y);
      var z = document.createElement("TD");
      var t = document.createTextNode(theUrls.parent);
      z.appendChild(t);
      document.getElementById("myTable").appendChild(z);
   });
   } else {
     const errorMessage = document.createElement('marquee');
     errorMessage.textContent = `Gah, it's not working!`;
     app.appendChild(errorMessage);
   }
}

request.send();
}); 

我收到错误:

Uncaught TypeError: data.forEach is not a function at 
XMLHttpRequest.request.onload

我想使用从上面第一个块代码中获得的 URL 并将其添加到:

  /Aud/1234/run/123456/result/pages/ + "page?url=" + https%3A%2F%2Fwww.abc.com%2Fat-work%2F'

我有用于带有查询参数的 API 调用的 API 数据,但我无法调用数据并且我收到错误消息。我做错了什么?

【问题讨论】:

  • 我在这里可能是错的,但我认为您应该从request.responseText 之类的响应中读取响应,而不是JSON.parse(this.response)。你能试试这个吗?你可能可以检查 fetch api,因为它比 XMLHttpRequest 更容易使用

标签: jquery html json api


【解决方案1】:

问题可能是因为

var data = JSON.parse(this.response);

你可以试试替换成

var data = JSON.parse(request.responseText)

由于响应存储在 reponseText 属性中。并检查您得到的带有查询参数的响应是否实际上是一个数组。因为 forEach 只存在于一个数组中。

你做得很好。但是,由于您使用的是 jquery,因此您可以通过更多地利用 jquery 方法来进一步减少代码。

$(document).ready(function($) {
  $('#theTable').append($('div', {class:"container"}));
  //i am using fetch here you can use jquery alternative $.get also
   fetch('/Aud/1234/run/123456/result/pages/')
        .then(function(response) {
            if(response.ok) {
              return response.json();
            } else {
               throw Error(`Request rejected with status ${res.status}`);
            }
        })
        .then(function(data){
             if(!Array.isArray(data)) {
                  throw Error('Response is not in correct format')
             }
             let allRowHTML = data.reduce(function(rowHTML, URI) {
                 rowHTML.concat(`<tr><td>${URI}</td></tr>`)
             }, '');
             $('#myTable').append(myTable);
        })
        .catch(funtion (err) {
          console.error(JSON.stringify(err));
        })
})

【讨论】:

  • 谢谢,但res.ok 中的res 是什么?
  • 对不起,它应该是响应错字。
猜你喜欢
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-21
  • 1970-01-01
相关资源
最近更新 更多