我试图在 AJAX 调用中使用 jQuery 循环遍历 JSON 对象,然后在 html 页面中打印对象。我遇到了这篇 stackoverflow 帖子,它向您展示了如何遍历 json 对象。这在一定程度上起作用。
我能够显示来自具有 id": 1 的对象的所有值,但在此之后我无法尝试显示更多值。例如,我想显示存储在 "id": 2 中的值和很快。
JSON 数据由https://openhardwaremonitor.org软件生成。
这是 JSON 数据在简短版本中的样子,这是完整版本
{
"id": 0,
"Text": "Sensor",
"Min": "Min",
"Value": "Value",
"Max": "Max",
"ImageURL": "",
"Children": [
{
"id": 1,
"Text": "LAPTOP-4CG0QVS4",
"Min": "",
"Value": "",
"Max": "",
"ImageURL": "images_icon/computer.png",
"Children": [
{
"id": 2,
"Text": "ASUS FX504GM",
"Min": "",
"Value": "",
"Max": "",
"ImageURL": "images_icon/mainboard.png",
"Children": []
},
{
"id": 3,
"Text": "Intel Core i7-8750H",
"Min": "",
"Value": "",
"Max": "",
"ImageURL": "images_icon/cpu.png",
"Children": [
{
"id": 4,
"Text": "Clocks",
"Min": "",
"Value": "",
"Max": "",
"ImageURL": "images_icon/clock.png",
"Children": [
{
这是我目前拥有的代码
<script>
var url = 'https://api.myjson.com/bins/sa41o';
$.ajax({
url: url,
method: 'GET',
}).done(function (result) {
var data = result.Children;
//console.log(result.Children.length);
var i = 0;
var hosData = "<table border='1'>";
hosData += "<tr>";
hosData += "<th>";
hosData += 'id';
hosData += "</th>";
hosData += "<th>";
hosData += 'Text';
hosData += "</th>";
hosData += "<th>";
hosData += 'Min';
hosData += "</th>";
hosData += "<th>";
hosData += 'Value';
hosData += "</th>";
hosData += "<th>";
hosData += 'Max';
hosData += "</th>";
hosData += "<th>";
hosData += 'ImageURL';
hosData += "</th>";
hosData += "</tr>";
for (i = 0; i < data.length; i++) {
hosData += "<tr>";
hosData += "<td>";
hosData += data[i].id;
hosData += "</td>";
hosData += "<td>";
hosData += data[i].Text;
hosData += "</td>";
hosData += "<td>";
hosData += data[i].Min;
hosData += "</td>";
hosData += "<td>";
hosData += data[i].Value;
hosData += "</td>";
hosData += "<td>";
hosData += data[i].Max;
hosData += "</td>";
hosData += "<td>";
hosData += data[i].ImageURL;
hosData += "</td>";
hosData += "</tr>";
}
hosData += "</table>";
$("#data").html(hosData);
}).fail(function (err) {
throw err;
});
<script
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data">
</div>
我似乎无法解决这个问题。
var data = result.Children
返回长度为 1,这是这里的问题,因为我期望长度大于 1。