Ajax:在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。
Ajax简单实现:
1.Controller
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/ajax")
public class AjaxController {
@RequestMapping("/login")//前往login.jsp页面
public String login() {
return "login";
}
@RequestMapping(value = "/a",produces="text/html;charset=UTF-8")
@ResponseBody
public String a(String name) {//账号验证
if("admin".equals(name)) {
return "ok";
}
else {
return "用户名错误";
}
}
@RequestMapping(value = "/b",produces="text/html;charset=UTF-8")
@ResponseBody
public String b(String password) {//密码验证
if("123456".equals(password)) {
return "ok";
}
else {
return "密码错误";
}
}
}
2.login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax登录验证</title>
<!-- 导入jquery -->
<script src="${pageContext.request.contextPath }/js/jquery-1.9.1.min.js"></script>
</head>
<script type="text/javascript">
function a() {
$.ajax({
// type:ajax默认请求方式为get
type:"post",
//url:发送请求的地址
url:"${pageContext.request.contextPath }/ajax/a",
//data:发送的数据
data:{"name":$("#userName").val()},
//success:发送成功后的回调函数
success:function(data){
if(data.toString()=="ok"){
$("#nameInfo").css("color","green");
}
else {
$("#nameInfo").css("color","red");
}
$("#nameInfo").html(data);
}
})
}
function b(){
$.ajax({
type:"post",
url:"${pageContext.request.contextPath }/ajax/b",
data:{"password":$("#password").val()},
success:function(data){
if(data.toString()=="ok"){
$("#passwordInfo").css("color","green");
}
else {
$("#passwordInfo").css("color","red");
}
$("#passwordInfo").html(data);
}
})
}
</script>
<body>
<!--
onblur 失去焦点时发生事件
onclick 点击时发生事件
-->
<p>用户名:</p>
<input type="text" id ="userName" onblur="a()"><span id="nameInfo"></span>
<p>密码:</p>
<input type="password" id ="password" onblur="b()"><span id="passwordInfo"></span>
</body>
</html>