javascript - 将 JSON 解析为 HTML 表时未定义

标签 javascript jquery html json ajax

我正在使用 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);
       }
   });
});

显示问题的附图 - enter image description here

json 未解析为 HTML 表,我在表中未定义。怎么了?

最佳答案

你得到的是字符串形式的 json,你必须先解析它

像这样:

 var json = JSON.parse($("#productDiv").html());

关于javascript - 将 JSON 解析为 HTML 表时未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41828916/

相关文章:

javascript - 即使在 AngularJS 中使用 ng-cloak,页脚模板也会闪烁

JavaScript BST 递归。如何删除引用为 "this"的节点类?

html - 嵌套表格中下拉菜单的 CSS 问题

jquery - 导航栏选项卡的自定义主题/颜色jquery-mobile

html - 如何以编程方式检测缩放事件并在当前页面的 Chrome 中设置缩放?

javascript - onMessage 不能在 React Native 中工作

javascript - 如何解析 JSON 数组以获取单个数组元素

javascript - 从字符串中删除除最后一个以外的所有小数

javascript - 在 Safari 和 Chrome 中跳转 div。 jQuery/Javascript

javascript - 我如何使用 jQuery 将特定的单词放入它们自己的 div 类中? (制作 Chrome 扩展程序)