使用ajax的作用就是不需要刷新整个界面就可以访问服务器拿到数据并实现局部的刷新
前端界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax实现异步验证</title>
</head>
<body>
<span>失去焦点验证输入号码的合法性</span><br>
<input type="text" id="moblephone" onblur="testOnblur()"/><span id="showerror"></span><br>
<span>点击验证向数据库中拿数据进行验证</span><br>
<input type="button" value="验证" onclick="confirmMoble()">
<script>
function testOnblur(){
var phone = document.getElementById("moblephone").value;
if(phone!=''){
if(!(/^1[0-9]{10}$/.test(phone))){
document.getElementById("showerror").innerHTML="号码格式不正确";
document.getElementById("moblephone").value='';
}
}
}
function confirmMoble(){
var phone= document.getElementById("moblephone").value;//获取号码值
var xhr=new XMLHttpRequest();//创建连接
//设置回调函数
xhr.onreadystatechange=callback;
xhr.open("post","confirmServlet",true);//向后台发送数据建立连接 参数[传递方式,服务器地址,是否异步]
//发送设置的请求头 固定格式
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
//发送的数据
xhr.send("moblephone="+phone);
function callback(){
//数据成功的标志
console.log(xhr.readyState);
if(xhr.readyState==4&& xhr.status==200){
var data = xhr.responseText;
if(data=='true'){
alert("号码成功");
}else{
alert("号码错误");
document.getElementById("moblephone").value="";
}
}
}
}
</script>
</body>
</html>
后端服务器的代码
package com.sofency.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class confirmServlet
*/
public class confirmServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收前端传进的数据
request.setCharacterEncoding("utf-8");//设置请求的编码
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");//响应的编码
//获取电话号码
String number = request.getParameter("moblephone");
//开始匹配
PrintWriter out=response.getWriter();
//判断并向前端发送数据判断是否成功
//此时的号码可已通过 数据库获取
if("XXXXXXXXXXX".equals(number)) {
out.print("true");
}else {
out.print("false");
}
out.flush();
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}