如何使用jquery获取一行json?

时间:2016-01-11 19:58:33

标签: jquery json

我有从源

返回的json
[{"Title":"Gross Wages","Last":"$40,000","MTD":"$40,000","QTD":"$40,000","YTD":"$40,000"},
{"Title":"Total Taxes","Last":"$50,000","MTD":"$50,000","QTD":"$50,000","YTD":"$50,000"},
{"Title":"Total Benefits","Last":"$60,000","MTD":"$60,000","QTD":"$60,000","YTD":"$60,000"},
{"Title":"Regular Hours","Last":"$450","MTD":"$450","QTD":"$450","YTD":"$450"},
{"Title":"OT Hours","Last":"57.5","MTD":"57.5","QTD":"57.5","YTD":"57.5"},
 {"Title":"New Hires","Last":"6","MTD":"6","QTD":"6","YTD":"6"},
{"Title":"Terminations","Last":"1","MTD":"1","QTD":"1","YTD":"1"}]

我希望能够只使用json的第一行。我可以像这样将所有行加载到我的表中。

$.getJSON(execOverview, function (json) {
            for (var i = 0; i < json.length; i++) {

                $.each(json[i], function (key, value) {
                    //Populate table row content
                        $('#execTbl tbody').append("<td>" + value + "</td>");
                });
                //Wrap elements
                $('#execTbl > tbody > td').wrapAll("<tr></tr>");
            }
        });

我只是不确定如何只将第一行加载到表中

1 个答案:

答案 0 :(得分:1)

试试这个。由于您只查找第一行(索引0),因此您不需要for阻止。只需检查大于零的长度。

if(json.length > 0)
{
   $.each(json[0], function (key, value) {
    //Populate table row content
   $('#execTbl tbody').append("<td>" + value + "</td>");
   });
   //Wrap elements  
$('#execTbl > tbody > td').wrapAll("<tr></tr>");
}

工作示例:https://jsfiddle.net/DinoMyte/6d5ry9br/3/