参考链接:http://shenymce.blog.51cto.com/337979/693868
Ajax.html页面
- <!DOCTYPE html>
- <html>
- <head>
- <title></title>
- <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
- <script type="text/javascript">
- var xmlhttp;
- function SubMit()
- {
- //非IE浏览器XMLHttpRequest对象的创建
- if (window.XMLHttpRequest)
- {
- xmlhttp=new XMLHttpRequest();
- }
- //IE浏览器XMLHttpRequest对象的创建
- else if(window.ActiveXObject)
- {
- var activename=["Msxml2.XMLHTTP","Msxml.XMLHTTP","Microsoft.XMLHTTP"];
- for (i=0;activename.length;i++)
- {
- try{
- xmlhttp=new ActiveXObject(activename[i]);
- break;
- }
- catch(e){}
- }
- }
- if (xmlhttp)
- {
- document.getElementById("message").innerHTML="开始用户名测试...";
- window.setTimeout('postxml()',2000); //2秒后执行
- }
- else
- {
- alert("你的浏览器不支持XMLHttpRequest对象");
- }
- }
- function godo()
- {
- //判断服务器是否有返回值
- if(xmlhttp.readyState == 4)
- //判断HTTP请求是否正确
- {
- if(xmlhttp.status == 200)
- {
- //获得服务器返回的数据
- document.getElementById("message").innerHTML=xmlhttp.responseText;
- }
- }
- }
- //采用get方式传递参数
- function getxml()
- {
- var uname=document.getElementById("UserName");
- xmlhttp.open("get","AjaxServlet?uname="+uname.value,true)
- xmlhttp.onreadystatechange=godo;
- xmlhttp.send(null);
- }
- //采用post方式传递参数
- function postxml()
- {
- var uname=document.getElementById("UserName");
- xmlhttp.open("post","AjaxServlet",true)
- xmlhttp.onreadystatechange=godo;
- xmlhttp.setRequestHeader ("Content-Type","application/x-www-form-urlencoded");
- xmlhttp.send("uname="+uname.value);
- }
- </script>
- </head>
- <body>
- <input type="text" id="UserName"/>
- <input type="button" value="用户名验证" onclick="SubMit();"/>
- <div id="message"></div>
- </body>
- </html>
AjaxServlet.java页面
- protected void processRequest(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html;charset=UTF-8");
- PrintWriter out = response.getWriter();
- try {
- String old=request.getParameter("uname");
- if(old == null || "".equals(old))
- {
- out.println("用户名不可以为空");
- }else{
- String name = new String(old.getBytes("ISO8859-1"),"gb2312");
- System.out.println(name);
- if(name.equals("123"))
- {
- out.println("用户名"+ name + "已经存在!");
- }else{
- out.println("用户名"+ name + "可以注册!");
- }
- }
- } finally {
- out.close();
- }
- }