一·ajax异步加载数据
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/static/jquery.js"></script>
<script>
//当页面加载后就执行函数
$(function (){
$("#btn").click(function (){
$.post({
url:"${pageContext.request.contextPath}/t3",
success:function (data) {
var html = "";
for (let i = 0; i < data.length; i++) {
html+="<tr>"+
"<td>"+ data[i].name + "<td>"+
"<td>"+ data[i].age + "<td>"+
"<tr>"
}
$("#data").html(html);
}
})
})
})
</script>
</head>
<body>
<div>
<table style="color: red">
<thead>
<tr>
<td>姓名</td>
<td>年龄</td>
</tr>
</thead>
<tbody id="data">
</tbody>
</table>
<br>
<span id="btn">导入数据</span>
</div>
</body>
</html>
去请求这个地址:?
@RequestMapping("/t3")
public List<User> test3(){
List<User> userList = new ArrayList<>();
User user1 = new User("何志康1号",1);
User user2 = new User("何志康2号",1);
User user3 = new User("何志康3号",1);
User user4 = new User("何志康4号",1);
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
return userList;
}
点击导入数据:
?
?就可以实现异步从后端加载数据!
二·ajax实验用户验证
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/static/jquery.js"></script>
<script>
function test(){
$.post({
url:"${pageContext.request.contextPath}/t2",
data:{"username":$("#username").val()},
success:function (data) {
if(data==="OK"){
$("#userInfo").css("color","green");
}else {
$("#userInfo").css("color","red")
}
$("#userInfo").text(data)
}
})
}
function test2(){
$.post({
url:"${pageContext.request.contextPath}/t2",
data:{"pwd":$("#pwd").val()},
success:function (data) {
if(data==="OK"){
$("#pwdInfo").css("color","green");
}else {
$("#pwdInfo").css("color","red")
}
$("#pwdInfo").text(data)
}
})
}
</script>
</head>
<body>
<div>
<form action="" method="post">
用户名:<input type="text" id="username" name="username" onblur="test()"> <span id="userInfo"></span> <br>
密码: <input type="password" id="pwd" name="pwd" onblur="test2()"> <span id="pwdInfo"></span> <br>
</form>
</div>
</body>
</html>
访问这个地址:
@RequestMapping("/t2")
public String login(String username,String pwd){
String msg = null;
if (username!=null){
if(username.equals("admin")){
msg = "OK";
}
else {
msg="用户名不正确";
}
}
if (pwd != null) {
if (pwd.equals("123456")){
msg = "OK";
}
else {
msg = "密码不正确";
}
}
return msg;
}
真正地应该去数据库里面查询再做判断,这里只进行一个简单的模拟!
?
?这样就实现了一个简单的ajax验证!
|