我编写了以下代码用于在 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
}
当前表格的外观:
最佳答案
您需要<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/