- 遍历一个数组,用$.each()来处理
- $.get请求后台数据进行处理
- 封装函数进行处理,解析Json生成tr
- 实现可以传递需要的字段
1、遍历一个数组,用$.each()来处理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
</head>
<body>
<table class="usertable">
<tbody></tbody>
</table>
</body>
</html>
<script type="text/javascript">
$(function(){
var needhtml = "";
var data = [
{
"Id":"01",
"UserName":"刘大姐",
"Number":"1234561111",
"Address":"北京广场",
"Class":"3号",
},
{
"Id":"02",
"UserName":"刘大姐",
"Number":"1234562222",
"Address":"上海广场",
"Class":"2号",
},
{
"Id":"03",
"UserName":"刘大姐",
"Number":"1234563333",
"Address":"广州广场",
"Class":"1号",
}
]
//为每一行赋值
$.each(data, function (index, item) {
needhtml += "<tr>";
needhtml += "<td>" + item.Id + "</td>";
needhtml += "<td>" + item.UserName + "</td>";
needhtml += "<td>" + item.Number + "</td>";
needhtml += "<td>" + item.Address + "</td>";
needhtml += "<td>" + item.Class + "</td>";
needhtml += "</tr>";
});
$(".usertable > tbody").html(needhtml);
})
</script>
2、 $.get请求后台数据进行处理
$.get("/Home/GetData", { currentPage: num }, function (result) {
var needhtml = "";
//为每一行赋值
$.each(result.data, function (index, item) {
needhtml += "<tr>";
needhtml += "<td>" + item.Id + "</td>";
needhtml += "<td>" + item.UserName + "</td>";
needhtml += "<td>" + item.Number + "</td>";
needhtml += "<td>" + item.Address + "</td>";
needhtml += "<td>" + item.Class + "</td>";
needhtml += "</tr>";
});
$(".usertable > tbody").html(needhtml);
});
3、封装函数进行处理,解析Json生成tr
//根据json生成tr
var ajParseTable = function (_jsondata) {
var needhtml = "";
$.each(_jsondata, function (index, item) {
needhtml += "<tr>";
for (var key in item) {
needhtml += "<td>" + item[key] + "</td>";
}
needhtml += "</tr>";
});
return needhtml;
}
//使用该方法
$.get("/Home/GetData", { currentPage: num }, function (result) {
//调用方法得到需要的html
var needhtml = ajParseTable(result.data);
$(".usertable > tbody").html(needhtml);
});
4、有些并不是返回多少个字段就显示到表格中我们可以在给予一个参数,传递需要显示的字段。
var ajParseTable = function (_jsondata,_needshow) {
var needhtml = "";
//如果传了数据,就取需要的字段
if (typeof (_needshow) != "undefined") {
$.each(_jsondata, function (index, item) {
needhtml += "<tr>";
for (var i = 0; i < _needshow.length; i++) {
needhtml += "<td>" + item[_needshow[i]] + "</td>";
}
needhtml += "</tr>";
});
}
else
{
//取json中所有的字段
$.each(_jsondata, function (index, item) {
needhtml += "<tr>";
for (var key in item) {
needhtml += "<td>" + item[key] + "</td>";
}
needhtml += "</tr>";
});
}
return needhtml;
}