我正在使用 jQuery Load 方法来获取外部 JSON。然后尝试将其内容显示为 HTML 表格。
json 文件“product.json”是 -
[
{
"User_Name": "John Doe",
"score": "10",
"team": "1"
},
{
"User_Name": "Jane Smith",
"score": "15",
"team": "2"
},
{
"User_Name": "Chuck Berry",
"score": "12",
"team": "2"
}
]
在我的 html 页面上我有一个按钮,单击时我执行 jQuery Load 方法以将此 json 提取到一个 div 中。然后我必须将此 json 显示为 HTML 表格。
HTML页面代码为:
<button id="productButton">Try</button>
<div id="productDiv"></div>
<table>
<tr>
<th>User_Name</th>
<th>score</th>
<th>team</th>
</tr>
</table>
jQuery 代码:
$("#productButton").click(function (e) {
$("#productDiv").load("product.json", function (response, status, xhr) {
var json = $("#productDiv").html();
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].User_Name + "</td>");
tr.append("<td>" + json[i].score + "</td>");
tr.append("<td>" + json[i].team + "</td>");
$('table').append(tr);
if (status == "error")
$("#textNoData").html("Error: " + xhr.status + ": " + xhr.statusText);
}
});
});
json 未解析为 HTML 表,我在表中未定义。怎么了?
最佳答案
你得到的是字符串形式的 json,你必须先解析它
像这样:
var json = JSON.parse($("#productDiv").html());
关于javascript - 将 JSON 解析为 HTML 表时未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41828916/