JQuery,JSON和$ .each - 字符串不连接

时间:2015-06-10 15:28:16

标签: javascript jquery json

所以,我有一个函数,当被调用时,在现有表的新行中添加一个表,完成由一个宁静的API以JSON格式返回的结果。

代码:

$(".transactionViewButton").each(function(){
    var $this = $(this);
    $this.on("click", function(){
        if($(this).closest("tr").next("tr").attr('id') != "itemsRow"){
            var rowAdd = "<tr id='itemsRow'><td colspan='8'><table class='table table-striped table-hover bureau-customer-table'><thead><tr><th>Item ID</th><th>Item Name</th><th>Cost</th><th>FSM Amount</th><th>End Cost</th></tr></thead><tbody>";

            $.getJSON("transactionItem.json", function(data){
                $.each(data, function (key, val){
                    rowAdd += "<tr><td>" + val.ID + "</td><td>" + val.Name + "</td><td>" + val.Cost + "</td><td>" + val.FSM+ "</td><td>" + val.EndCost + "</td></tr>";
                });
            });
            rowAdd += "</tbody></table></td></tr>";
            $(this).closest("tr").after(rowAdd);
        } else {
            $(this).closest("tr").next("tr").remove();
        }
    });
});

JSON测试数据:

[{
    "ID": "123",
    "Name": "Food Item 1",
    "Cost": "0.50",
    "FSM": "0.00",
    "EndCost": "0.50"
  },{
    "ID": "124",
    "Name": "Food Item 2",
    "Cost": "0.50",
    "FSM": "0.00",
    "EndCost": "0.50"
  },{
    "ID": "125",
    "Name": "Food Item 3",
    "Cost": "0.50",
    "FSM": "0.00",
    "EndCost": "0.50"
}]

该函数的作用与添加新表,标题行和结束行一样多。如果再次触发,它也会删除新行。

问题出在$.each部分。我知道它接收JSON数据是因为在rowAdd +=之前插入警报会导致每个记录的响应。它只是没有将实际的表行添加到每个记录的rowAdd字符串中。就像它只是简单地跳过那条线。此外,也没有JavaScript错误。那么,我错过了什么?

1 个答案:

答案 0 :(得分:1)

$.get是异步的。这意味着所有依赖于请求结果的代码都需要放在回调中。试试这个:

$.getJSON("transactionItem.json", function(data){
    var rowAdd = "<tr id='itemsRow'><td colspan='8'><table class='table table-striped table-hover bureau-customer-table'><thead><tr><th>Item ID</th><th>Item Name</th><th>Cost</th><th>FSM Amount</th><th>End Cost</th></tr></thead><tbody>";

    $.each(data, function (key, val){
        rowAdd += "<tr><td>" + val.ID + "</td><td>" + val.Name + "</td><td>" + val.Cost + "</td><td>" + val.FSM+ "</td><td>" + val.EndCost + "</td></tr>";
    });

    rowAdd += "</tbody></table></td></tr>";
    $(this).closest("tr").after(rowAdd);
});