日期:2014-05-16 浏览次数:20579 次
<html> <head> <script type="text/javascript"> var xmlHttp;//定义个XMLHttp //创建一个XMLHttprequest function createXMLHttpRequest() { //IE系列的浏览器 if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } //firefox等浏览器 else if (window.XMLHttpRequest) { //实例化一个XMLHttprequest。 xmlHttp = new XMLHttpRequest(); } } //启动Ajax请求--GET function startRequestGet() { createXMLHttpRequest(); //注册回调方法 xmlHttp.onreadystatechange = handleStateChange; var userName = document.getElementById("names").value ; //设置提交方式,此处用的是GET xmlHttp.open("GET", "ajaxAction?name="+userName, true); xmlHttp.send(null); } //启动Ajax请求--POST function startRequestPost() { createXMLHttpRequest(); //注册回调方法 xmlHttp.onreadystatechange = handleStateChange; var userName = document.getElementById("names").value ; //设置提交方式,此处用的是GET xmlHttp.open("GET", "ajaxAction", true); xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlHttp.send("name="+userName); } function handleStateChange() { //判断是否和服务器端的交互完成,还要判断服务器段是否正确返回数据 if(xmlHttp.readyState == 4) { //表示和服务器端的交互以完成 if(xmlHttp.status == 200) { var message = xmlHttp.responseText; //获得值的显示位置 var div = document.getElementById("message"); //在该位置显示值 div.innerHTML = message; } } } </script> </head> <body> This is my Test AJAX page!! <br> <form action="ajaxAction" method="get"> <table> <tr> <td> <input type="text" name="name" id="names" value="" onblur="startRequestGet()"> </td> <td ><div id="message"></div> </td> <td> <input type="submit" value="submit"> </td> <td> <input type="button" value="button" onclick="startRequest()"> </td> </tr> </table> </form> </body> </html>
public class AjaxAction extends ActionSupport{ private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String execute() throws Exception { HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=gbk");//解决乱码问题 response.setCharacterEncoding("GBK");//解决乱码问题 PrintWriter out = response.getWriter(); if(name.equals("cht")){ out.println(name+"用户名被占用"); System.out.println(name+"用户名被占用"); }else{ out.println(name+"该用户名可用"); System.out.println(name+"该用户名可用"); } out.close(); return super.execute(); } }