Ajax 代码模板:
清单一:index.jsp 代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript"> var xmlHttp; function verify(){ var username=document.getElementById("username").value; try { xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari } catch (e){ try{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer } catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch (e){ alert("您的浏览器不支持AJAX!"); return false; } } } //注册回调函数 xmlHttp.onreadystatechange=callback; //设置连接信息 var url = encodeURI(encodeURI("check?username="+username)); //页面端两次encodeURI //xmlhttp.setRequestHeader( "Content-Type", "text/html;charset=UTF-8" );//设置编码 xmlHttp.open("GET",url,true); //发送数据,开始与服务器端交互 xmlHttp.send(null); } //回调函数代码如下: function callback(){ //判断交互是否完成 if(xmlHttp.readyState==4){ //判断http的交互是否成功 if(xmlHttp.status==200){ //获取服务器端的纯文本数据 var responseText=xmlHttp.responseText; document.getElementById("show").innerHTML=responseText; }else{ alert("出错了"); } } } </script> </head> <body> <form action="" > 用户名: <input type="text" name="username" onBlur="verify();" id="username"><div id="show"></div><br> 密码: <input type="text" name="password"><br> <input type="submit"> </form> </body> </html>
清单二:Servlet代码
package com.asm.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AjaxServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String username = URLDecoder.decode(request.getParameter("username"),
"UTF-8");
PrintWriter out = response.getWriter();
out.write("你输入的用户名为:<font color='red'>" + username+"</font>");
}
}