我正在尝试将json数据从php文件传递到html表中。我让它工作,但我的所有数据都被传递到一行中。如何使每个值都放入新行中?
杰森:
{"users":[{"key":["3108","3098","3039","3033","2508"]}]}
jquery代码:
$(document).ready(function(){
var url="localhost/testfile.php";
var table='<table>';
$.getJSON(url,function(data){
$.each( data.users, function( index, item){
table+="<thead><tr><th>Key</th></tr></thead><tbody><tr><td>"+item.key+"</td></tr></tbody>";
table+='</table>';
$("#jsondata").html( table );
更新:如果在用户中我有多个条目,正确的格式将是:
$.each(data.users, function(index, item) {
table += "<tr><td>" + item.key + "</td>"+"<td>" + item.x + "</td></tr>"
还是我弄错了格式?
任何指导都非常感谢!
您正在循环外部创建表标记(正确)。您还应该创建thead
和标题行,然后仅在循环中创建tr
行。你的第二个问题是你在循环的每次迭代中设置#jsondata
div的HTML。您应该在循环后设置它:
$.getJSON(url,function(data){
var table = '<table><thead><tr><th>Key</th></tr></thead><tbody>';
$.each( data.users, function( index, item){
table += "<tr><td>"+item.key+"</td></tr>";
});
// after the loop, close your tbody and table tags
table += '</tbody></table>';
// then AFTER the loop, you set the data to the table.
$("#jsondata").html( table );
});
编辑:您没有获得正确的数据,让我们看看您的JSON结构:
{
"users": [
{
"key": [
"3108",
"3098",
"3039",
"3033",
"2508"
]
}
]
}
因此,您可以从上面的"漂亮"JSON中看到,您实际上有两个级别的数组,因此您的循环需要适应这一点。如果您只希望users
有一个条目,即key
,那么只需将您的$.each()
更改为以下内容:
$.each(data.users.key, function(index, item) {
table += "<tr><td>" + item + "</td></tr>";
});
我认为这将起作用:
<script type="text/javascript">
$(document).ready(function(){
var url="localhost/testfile.php";
var tableHeaders='<tr><th>Key</th></tr>';
var tableBody = '';
$.getJSON(url,function(data){
$.each(data.users, function( index, item){
tableBody+="<tr><td>"+item.key+"</td></tr>";
});
});
//Adding headers to the table
$("table thead").html(tableHeaders);
//Adding rows to the table
$("table tbody").html(tableBody);
});
</script>
<table>
<thead></thead>
<tbody></tbody>
</table>