一个简单的ajax调用,页面上一个输入框,输入email地址后,调用ajax请求服务端对email做简单校验,服务器端用一个servlet响应和校验,然后将校验结果显示给用户
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <Meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <div style="absolute; left:200px; top:200px"> <table> <tr> <td> <input type="text" id="mailIpt"/> </td> <td> <input type="button" onclick="javascript:checkMail()"/> </td> </tr> </table> </div> </body> <script type="text/javascript"> function createXhr(){ if(window.ActiveXObject){ return new ActiveXObject("Microsoft.XMLHTTP"); }else if(window.XMLHttpRequest){ return new XMLHttpRequest(); } } var xhr=null; function checkMail(){ xhr=createXhr(); var url="vm?mailIpt="+escape(document.getElementById("mailIpt").value); xhr.open("GET",url); //XMLHttpRequest.open("GET",url,true) true是默认的,表示异步回调 xhr.onreadystatechange=displayStatus; xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(null); //get方式请求体设置为null,post需发送请求体 } function displayStatus(){ if(xhr.readyState==4){ //readyState服务端状态,0无状态,1建立连接,2准备发送数据,3正在发送数据,4请求响应完毕 if(xhr.status==200){//status客户端状态,200数据已存于缓存,400url出错,500内部错误 //var status=document.getElementById("mailFormatStatus"); var mailStatus=xhr.responseText; if(mailStatus=="true") alert("ok"); else alert("check mail Failed"); } } } </script> </html>
servlet代码如下:
package com; import java.io.IOException; import java.io.PrintWriter; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ValidEmailFormatServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ response.setContentType("text/plain;charset=gbk"); String mail=(String)request.getParameter("mailIpt"); String status="false"; Pattern p=Pattern.compile("\\S+@\\S+"); Matcher m=p.matcher(mail); if(m.matches()) status="true"; PrintWriter pw=response.getWriter(); pw.print(status); pw.close(); } }
web.xml中的servlet定义:
<servlet> <servlet-name>ValidEmailFormatServlet</servlet-name> <servlet-class>com.ValidEmailFormatServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ValidEmailFormatServlet</servlet-name> <url-pattern>/vm</url-pattern> </servlet-mapping>原文链接:https://www.f2er.com/ajax/163776.html