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 proce***equest(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();
- }
- }