簡體   English   中英

將json傳遞到html表:數據全部放在一行中

[英]Passing json to html table: Data all in a single row

我正在嘗試將json數據從php文件傳遞到html表中。 我可以使用它,但是我所有的數據都被傳遞到一行中。 如何使每個值放入新行中?

JSON:

{"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和title行,然后僅在循環中創建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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM