【发布时间】: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 更容易使用