【发布时间】:2020-04-26 13:17:22
【问题描述】:
我正在尝试使用 XMLHttpRequest 从 URL (GET API) 以 JSON 形式获取数据,然后在 HTML 表中显示该数据。
我已经能够获取数据,但无法正确显示。
我的表格显示为:
名称 ID 生成类型区域
名称 ID 生成类型区域
代替:
名称 ID 生成类型区域
Bulabasaur 1 第一草关东
我的 JSON 数据返回为:
[{
ability: "Overgrow",
category: "Seed"
description: "Bulbasaur can be seen napping in bright sunlight. There is a seed on its back. By soaking up the sun's rays, the seed grows progressively larger.",
gender: "M",
generation: "First",
height: "2' 04''",
id: 1,
name: "Bulbasaur",
picture: "bulbasaur.jpg",
region: "Kanto",
type: "Grass, Poison",
weakness: "Fire, Flying, Ice, Psychic",
weight: "15.2"
}]
这是我的 JavaScript 代码:
var rootURL = "http://localhost:8080/WorksheetPokemon/rest/pokemon";
var xhttp = new XMLHttpRequest();
function pokemonTable(){
xhttp.open('GET', rootURL, true);
xhttp.onreadystatechange = function() {
//console.log(this.responseText);
if (xhttp.readyState === XMLHttpRequest.DONE) {
var status = xhttp.status;
if (status === 0 || (status >= 200 && status < 400)) {
var json = JSON.parse(xhttp.responseText);
createTable(json);
} else {
console.log("Error");
}
}
};
xhttp.send();
}
function createTable(json) {
console.log(json);
var tableBody = document.getElementById("table_body");
// Populate table
json.forEach((row) => {
var tr = document.createElement("tr");
Object.keys(row).forEach((cell) => {
var td = document.createElement("td");
td.textContent = cell;
tr.appendChild(td);
});
tableBody.appendChild(tr);
});
}
document.addEventListener("DOMContentLoaded", pokemonTable());
【问题讨论】:
-
但不能正确显示是什么意思?您能否向我们展示一下表格应该是什么样子以及 JSON 中的数据是如何构成的?
-
所以我的表应该是:Name ID Generation Type Region Bulbasaur 1 First Grass Kanto 但它回来了:Name ID Generation Type Region Name ID Generation Type Region
-
我的 JSON 数据返回为: 能力:“过度生长” 类别:“种子” 描述:“在明亮的阳光下可以看到大头龙正在打盹。它的背上有一颗种子。通过吸收太阳的射线,种子逐渐变大。”性别:“M” 世代:“第一” 身高:“2' 04''” id:1 姓名:“Bulbasaur” 图片:“bulbasaur.jpg” 地区:“关东” 类型:“草、毒” 弱点:“火,飞行,冰,精神”重量:“15.2”
标签: javascript json xmlhttprequest