我从AJAX调用中得到以下JSON响应:
{"items":[{"name":"MP 201SPF_1C","productNo":"123","commerceItemQty":1,"price":"$350.00","leaseOrNot":"false"},{"name":"MP 201SPF_1C","productNo":"456","commerceItemQty":4,"price":"$1,400.00","leaseOrNot":"false"},{"name":"MP 201SPF_1C","productNo":"789","commerceItemQty":4,"price":"$1,400.00","leaseOrNot":"true"}]}
这是我的代码:
$.getJSON(ajaxResponse, function (data)
{
var tr;
for (var i = 0; i < data.length; i++)
{
tr = $('<tr/>');
tr.append("<td><h3>" + data[i].name + "</h3>""<p><strong>" + data[i].productNo + "</strong></p>""<div>" + data[i].leaseOrNot + "</div></td>");
tr.append("<td>" + data[i].commerceItemQty + "</td>"); tr.append("<td>" + data[i].price + "</td>"); $('table').append(tr);
}
});
我需要将上面的JSON数据附加到表中。我该怎么做?请帮忙!
答案 0 :(得分:0)
var json={"items":[{"name":"MP201SPF_1C","productNo":"123","commerceItemQty":1,"price":"$350.00","leaseOrNot":"false"},{"name":"MP201SPF_1C","productNo":"456","commerceItemQty":4,"price":"$1,400.00","leaseOrNot":"false"},{"name":"MP201SPF_1C","productNo":"789","commerceItemQty":4,"price":"$1,400.00","leaseOrNot":"true"}]}
var table="<table><thead><tr><th>head1</th>.....</tr></thead><tbody>"
for(var i=0;i<json.items.length;i++){
table+="<tr><td>"+json.items[i]["key name1"]+"</td>.........</tr>"
}
table+="</tbody></thead>";
document.getElementsByTagName("body")[0].innerHTML=table;
$.getJSON(ajaxResponse, function (data)
{
var tr;
for (var i = 0; i < data.items.length; i++)
{
tr = $('<tr/>');
tr.append("<td><h3>" + data.items[i].name + "</h3>""<p><strong>" + data[i].productNo + "</strong></p>""<div>" + data.items[i].leaseOrNot + "</div></td>");
tr.append("<td>" + data.items[i].commerceItemQty + "</td>"); tr.append("<td>" + data.items[i].price + "</td>"); $('table').append(tr);
}
});
答案 1 :(得分:0)
当数组在items对象中时,你需要迭代items对象:
$.each(json.items,function(index,item){
console.log(item);
tr = $('<tr/>');
tr.append("<td><h3>" + item.name + "</h3><p><strong>" + item.productNo + "</strong></p><div>" + item.leaseOrNot + "</div></td>");
tr.append("<td>" + item.commerceItemQty + "</td>"); tr.append("<td>" +item.price + "</td>"); $('table').append(tr);
})