具有查询参数的API

时间:2018-09-13 04:32:44

标签: jquery html json api

当我运行下面的代码时,没有错误的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数据,但是我无法调用该数据,并且出现错误。我在做什么错了?

1 个答案:

答案 0 :(得分:0)

问题可能是由于

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