将JSON放入表行

时间:2013-04-29 14:52:16

标签: javascript jquery json

那么,为什么这段代码不起作用?我复制它为jsfiddle,但它不工作..包括最新的库,所以我真的不知道为什么它不工作..; /

代码:

<html>

    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
        <script>
            var jsondata = $.parseJSON('{"response":[["name0","id0","amt0"],["name1","id1","amt1"]]}');
            $.each(jsondata.response, function (i, d) {
                var row = '<tr>';
                $.each(d, function (j, e) {
                    row += '<td>' + e + '</td>';
                });
                row += '</tr>';
                $('#table tbody').append(row);
            });
        </script>
    </head>

    <body>
        <div id="myDiv">
            <table id="table">
                <thead>
                    <tr>
                        <th>header1</th>
                        <th>header2</th>
                        <th>header3</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </body>

</html>

1 个答案:

答案 0 :(得分:2)

您需要将代码包装在:

$(document).ready(function() {

    //code here
    var jsondata=$.parseJSON('{"response":[["name0","id0","amt0"],["name1","id1","amt1"]]}');

    $.each(jsondata.response, function(i, d) {
        var row='<tr>';
        $.each(d, function(j, e) {
             row+='<td>'+e+'</td>';
        });
        row+='</tr>';
        $('#table tbody').append(row);
    });

});

您的代码有效:http://jsfiddle.net/ayqcf/