jquery - 无法使用 jQuery 正确打印 HTML 表中的 JSON 响应

标签 jquery html json html-table getjson

我编写了以下代码用于在 HTML 页面中打印 JSON。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $.getJSON("http://localhost:8080/json",function(result){
    $.each(result, function(i, field){
      $("tr").append(field + " ");
    });
  });
});
</script>
</head>
<body>
  <table id="table">
    <tr>
      <th>market</th>
      <th>buy</th>
      <th>sell</th>
      <th>currency</th>
      <th>volume</th>
    </tr>
  </table>
  <div></div>
</body>
</html>

我能够打印 JSON 响应值,但无法在表中正确打印它们。

JSON 响应格式:

{
  "market": 1309480,
  "buy": 1309480,
  "sell": 1280017,
  "currency": "INR",
  "volume": 2253.4518854
}

当前表格的外观:

enter image description here

最佳答案

您需要<td>标签来显示表格中的内容。 <th>是表头标签。

尝试以下:

$.getJSON("http://localhost:8080/json",function(result){
        var tr = '<tr>';  //create tr tag 
        $.each(result, function(i, field){
            tr += '<td>' + field +'</td>';  //loop through the result and create <td>
        });
        tr += '</tr>';  //close tr tag
        $('#table').append(tr);  // append it to table
}

另外,我很确定您可能需要多列(即,如果您的结果是多个)。为此,您需要使用 2 个循环。试试看。创建 fiddle 供引用:https://jsfiddle.net/bipen/3prfj474/ ;)

关于jquery - 无法使用 jQuery 正确打印 HTML 表中的 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47770647/

相关文章:

用户添加的 JavaScript 保存表行

javascript - 在动态添加的 DOM 元素上使用点击事件

html - 我可以在 CSS 中编写自己的伪函数吗

json - Play : How to implement a conditional JSON validator

css - 在 Scrapy 的 JSON 导出中启用重音符号?

jQuery 按类选择 VS 按属性选择

jquery - Zurb Foundation Accordion 嵌套在 Accordion 内部

jquery - 使用 Bootstrap 3 实现 Mmenu

html - 无法将内容放入 Bootstrap 4 的容器中

javascript - 使用 JavaScript 和 JSON 在 Web 应用程序中进行本地化