本文內容摘自:《Java Web開發教程——入門與提高篇(JSP+Servlet)》
下面以註冊過程中使用者名稱是否存在的驗證為例介紹AJAX的應用。功能描述:使用者註冊的使用者名稱不允許重複,所以在使用者提交時候需要判斷。為了讓使用者早知道結果,在使用者輸入使用者名稱之後就應該進行判斷,可以採用AJAX進行處理。假設:為了簡化代碼,該執行個體的驗證過程不使用資料庫,並且也不使用專門的JavaBean,直接在Servlet中驗證,假設已有使用者“zhangsan”、“lisi”和“wangwu”。執行個體包含兩個檔案:l 介面檔案;l 伺服器端處理檔案。註冊介面的代碼如下:<%@ page language="java" pageEncoding="gb2312"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'register.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"> --> </head> <script language="javaScript">var xMLHttpRequest=false;function createXMLHttpRequest(){ if(window.XMLHttpRequest){ // Mozilla瀏覽器 xMLHttpRequest = new XMLHttpRequest(); }else if(window.ActiveXObject){ try{ xMLHttpRequest = new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){ try{ xMLHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){} } }}function processResponse(){ if(xMLHttpRequest.readystate==4){ // 判斷對象狀態 if(xMLHttpRequest.status==200){ // 資訊已經返回,開始處理資訊 var res = xMLHttpRequest.responseText; //window.alert(res); document.getElementById("userlabel").innerText=res; }else{ // 頁面不正常 window.alert("您所請求的頁面有異常!"); } }}function usercheck(){ createXMLHttpRequest(); xMLHttpRequest.open("GET","check?username="+document.registerform.username.value,true); xMLHttpRequest.onreadystatechange=processResponse; //指定響應函數 xMLHttpRequest.send(null); //發送請求} </script> <body> <form name="registerform" action="register" method="post"> <P> 註冊</P><P>使用者名稱: <input type="text" name="username" onClick="usercheck()"><label for=username id="userlabel">不可為空</label></P><P> 性別:<input type="radio" checked="checked" value="男" name="sex">男 <input type="radio" value="女" name="sex">女</P><p> <input type="submit" value="註冊"></p></form> </body></html>伺服器端的主要代碼如下(Servlet的部分代碼): public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("gb2312"); String username = request.getParameter("username"); response.setContentType("text/html;charset=gb2312"); PrintWriter out = response.getWriter(); if(username.equals("zhangsan") ||username.equals("lisi") ||username.equals("wangwu")){ out.println("使用者名稱已經被佔用!"); }else { out.println("使用者名稱可以使用!"); } out.flush(); out.close(); }
上一講:
第二十一講 Ajax互動的基本過程下一講:JavaBean李緒成 CSDN Blog:http://blog.csdn.net/javaeeteacher邀請您為好友:http://student.csdn.net/invite.php?u=124362&c=7be8ba2b6f3b6cc5