【问题标题】:Not able to print JSON Response in HTML table properly using jQuery无法使用 jQuery 在 HTML 表中正确打印 JSON 响应
【发布时间】:2018-05-26 00:31:48
【问题描述】:

我为在 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
}

当前表格的外观:

【问题讨论】:

  • tr 中不需要td 吗?您还将它们附加到标题所在的同一位置。您应该使用theadtbody
  • @N.Ivanov 你能详细说明一下吗?

标签: jquery html json html-table getjson


【解决方案1】:

您需要&lt;td&gt; 标签来显示表格中的内容。 &lt;th&gt; 是表头标签。

试试下面:

$.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 个循环。试试看。创建小提琴供参考:https://jsfiddle.net/bipen/3prfj474/ ;)

【讨论】:

  • 你能帮我处理一下 HTML 代码吗?由于我无法看到任何输出,使用您建议的更改。
  • @AlapanDas 等等,出现语法错误。更新答案请检查。
  • @AlapanDas 另外,如果你的结果是一个数组,我认为你想在多列中显示它。这是一个示例小提琴。 jsfiddle.net/bipen/3prfj474
  • 我无法使用您建议的代码获得输出。我在这里写了代码。你能调查一下,让我知道我在哪里犯了错误。 jsfiddle.net/xt3pt6h2
  • 老兄!!! data 应该是 result。在这里更新小提琴。 jsfiddle.net/bipen/xt3pt6h2/2 。此外,如果您的结果是array,这将有效,否则上述结果将有效。
【解决方案2】:

给你一个解决方案

var result = {
  "market": 1309480,
  "buy": 1309480,
  "sell": 1280017,
  "currency": "INR",
  "volume": 2253.4518854
};

//$.getJSON("http://localhost:8080/json",function(result){
  $('#table').append('<tr/>');
  $.each(result, function(i, field){
    $('#table').find('tr:last').append('<td>' + field + '</td>');    
  });
//});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
  <tr>
    <th>market</th>
    <th>buy</th>
    <th>sell</th>
    <th>currency</th>
    <th>volume</th>
  </tr>
</table>
<div></div>

我刚刚注释掉了 AJAX 调用,请取消注释并删除结果变量。

首先将tr 附加到表中,然后使用jQuery last 选择器获取最后附加的tr 并将表附加到td 数据。

希望这会对你有所帮助。

【讨论】:

  • @shailaditya 谢谢它对我有用。只是一个快速的问题,我想插入一个静态值,比如行的第一个元素,我该怎么做?
  • @AlapanDas 同样你可以使用:first
【解决方案3】:

您可以在其中插入标签&lt;td&gt;

$("tr").append(field + " ");

像这样:

$("tr").append("<td>" + field + "</td>");

【讨论】:

    猜你喜欢
    • 2019-10-30
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多