ajax:异步刷新技术,可以在步刷新整个页面的前提下,刷新部分页面,节省资源
环境搭建:
1、搭建好SpringMVC的环境,不赘述,可观看SpringMVC配置
2、创建只返回数据的controller类
@RestController //使用该注解修饰,只返回数据不跳转页面
public class ajaxController {
@RequestMapping("ajax")
public List<user> getUser() {
List<user> userList = new ArrayList<user>();
userList.add(new user("yzx",23,"杭州"));
userList.add(new user("jay",40,"台湾"));
userList.add(new user("zhangsan",25,"北京"));
userList.add(new user("lisi",27,"上海"));
// String s = JSON.toJSONString(userList);
return userList;
}
}
3、创建jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>studentInfo</title>
<script src="${pageContext.request.contextPath}/js/jquery-1.11.0.min.js"></script>
</head>
<body>
<table>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>住址</th>
</tr>
<tbody id="mianTable">
</tbody>
</table>
<input type="button" value="加载数据" id="getInfo">
</body>
<script>
$("#getInfo").click(function () {
$.post("${pageContext.request.contextPath}/ajax", function (data) {
var html = "";
for (let i = 0; i < data.length; i++) {
html += "<tr>" +
"<td>" + data[i].name + "</td>" +
"<td>" + data[i].age + "</td>" +
"<td>" + data[i].address + "</td>" +
"</tr>";
}
alert(html);
$("#mianTable").html(html);
})
});
</script>
</html>

4、测试

网友评论