如圖:
ajax解析json并寫入table代碼模闆:
function find() {
$.ajax({
url: "/CustomerController/findCustomerByConditionWithAjax",
type: "POST",
data: {idCon: $("input[name='idCon']").val(), nameCon: $("input[name='nameCon']").val()},
dataType: 'json',
success: function (data) {
//清除table上一次查詢的内容
$("#customerTable tr:not(:first)").empty();
// 解析controller傳回的json資料并寫入table
$.each(data,function (index,item) {
var id= $("<td></td>").append(item.id);
var name=$("<td></td>").append(item.name)
var gender=$("<td></td>").append(item.gender)
var address=$("<td></td>").append(item.address)
$("<tr></tr>").append(id).append(name).append(gender).append(address).
appendTo($("table tbody").first());
})
}
})
}

js代碼:
$.each(data,function (index,item) {
var id= $("<td></td>").append(item.id);
var name=$("<td></td>").append(item.name)
var gender=$("<td></td>").append(item.gender)
var address=$("<td></td>").append(item.address)
$("<tr></tr>").append(id).append(name).append(gender).append(address).
appendTo($("table tbody"));
})
可以在浏覽器f12打開,看源代碼,找到原因:table裡有兩個tbody,要做個選擇:
appendTo($("table tbody").first());