概述
在表单验证中,在没有Ajax出现前,都必须提交表单以后才能验证表单,在用了Ajax技术以后可以不用刷新页面也能异步提交数据给服务器 ,非常方便,这是一个验证Demo
Jsp 页面:
<%--
Created by IntelliJ IDEA.
User: Yisa
Date: 16/8/26
Time: 下午10:24
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Test</title>
<script>
var XMLHttpReq = false;
function createXMLHttpRequest(){
if(window.XMLHttpRequest){
XMLHttpReq = new XMLHttpRequest();
}else if(window.ActiveXObject){
try{
XMLHttpReq = new ActiveXObject("MSXML2.XMLHTTP");
}catch(e){
try{
XMLHttpReq = new ActiveXObject("Mircsoft.XMLHTTP");
}catch(e1){}
}
}
}
function sendRequest(url){
createXMLHttpRequest();
XMLHttpReq.open("GET",url,true);
XMLHttpReq.onreadystatechange = processResponse;
XMLHttpReq.send(null);
}
function processResponse(){
if(XMLHttpReq.readyState == 4){
if(XMLHttpReq.status == 200){
var result = XMLHttpReq.responseText;
if(result=='true'){
alert('可以');
}
else
alert('不可以');
}
}
}
function check(obj){
var userid = obj.value;
if(userid == ""){
window.alert("用户名不能为空");
return false;
}else{
sendRequest("servlet/TestServlet?username="+userid);
}
}
</script>
</head>
<body>
<form >
输入: <input type="text" name ="username" onblur="check(this)" value="输入用户名">
</form>
</body>
</html>
Servlet验证:
/**
* Created by Yisa on 16/8/26.
*/
@WebServlet(name = "TestServlet")
public class TestServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("username");
if(name.equals("admin")){
out.print(true);
}
else{
out.print(false);
}
out.flush();
out.close();
}
}
Jquery版本
jquery版本封装了ajax方法,与服务器的数据交换可以用json解析,代码清晰许多
Servlet的返回格式转换为json
if(name.equals("admin")){
System.out.println("Herehaha");
String Re = "{\"success\":true,\"msg\":\"haha\"}";
out.print(Re);
}
else{
String Re = "{'success':false,'msg':'失败'}";
out.print(Re);
}
out.flush();
out.close();
Code:
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.js"></script>
<script>
$(document).ready(function () {
$("#username").blur(function () {
$.ajax({
type:"GET",
url:"servlet/TestServlet?username="+$("#username").val(),
dataType: "json",
success: function (data) {
alert(data);
if(data.success==true){
alert("chenggong");
}
else{
alert("shibai,"+data.msg);
}
},
})
})
});
</script>