ajax json jquery解析後臺返回的陣列
阿新 • • 發佈:2019-01-09
<script type="text/javascript" src="${basepath }/js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url:"testJson",
type:"post",
data:{"username":"zhangsan","age":"18"},
dataType:"json",
error:function(){alert("出錯啦")},
success:function(data){
alert("成功");
$("table").css("display","");
$.each(data,function(i,user){
var row=$("#template").clone();
row.find("#username").text(user.userName);
row.find("#password").text(user.userPass);
row.find("#age").text(user.age);
row.find("#email").text(user.email);
row.find("#sex").text(user.sex);
row.find("#address").text(user.address);
row.find("#postcode").text(user.postcode);
row.appendTo($("#tables"));
});
}
});
});
});
</script>
</head>
<body>
<button>點選我返回json陣列</button>
<div>aa</div>
<table border="1" cellspacing="1" style="display:none" id="tables">
<tr>
<td>username</td>
<td>password</td>
<td>age</td>
<td>email</td>
<td>sex</td>
<td>address</td>
<td>postcode</td>
</tr>
<tr id="template">
<td id="username"></td>
<td id="password"></td>
<td id="age"></td>
<td id="email"></td>
<td id="sex"></td>
<td id="address"></td>
<td id="postcode"></td>
</tr>
</table>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url:"testJson",
type:"post",
data:{"username":"zhangsan","age":"18"},
dataType:"json",
error:function(){alert("出錯啦")},
success:function(data){
alert("成功");
$("table").css("display","");
$.each(data,function(i,user){
var row=$("#template").clone();
row.find("#username").text(user.userName);
row.find("#password").text(user.userPass);
row.find("#age").text(user.age);
row.find("#email").text(user.email);
row.find("#sex").text(user.sex);
row.find("#address").text(user.address);
row.find("#postcode").text(user.postcode);
row.appendTo($("#tables"));
});
}
});
});
});
</script>
</head>
<body>
<button>點選我返回json陣列</button>
<div>aa</div>
<table border="1" cellspacing="1" style="display:none" id="tables">
<tr>
<td>username</td>
<td>password</td>
<td>age</td>
<td>email</td>
<td>sex</td>
<td>address</td>
<td>postcode</td>
</tr>
<tr id="template">
<td id="username"></td>
<td id="password"></td>
<td id="age"></td>
<td id="email"></td>
<td id="sex"></td>
<td id="address"></td>
<td id="postcode"></td>
</tr>
</table>
</body>
controller:
@ResponseBody
@RequestMapping("testJson")
public List<User> testJson(String username,String age){
System.out.println(username+"---"+age);
List<User> userList=userService.getUsers();
return userList;
}
這裡注意的是第一次進入頁面時只有一個button按鈕,表格進來時是隱藏的。當點選button後,從後臺查詢出list集合,以json陣列方式傳到前端,在前端迴圈將值顯示在表格中並顯示出來。
var row=$("#template").clone();表示複製模板,row.find("#username").text(user.userName);表示在行中找到一列id叫username的,並對其進行內容賦值。此處用$.each(data,function(i,user){})這裡的user已經是迴圈過的物件,相當於user=data[i],可直接拿出來用.最後再通過row.appendTo($("#tables"));將模板的內容新增到表格中。
效果如下: