1. 程式人生 > >Ajax案例-基於HTML,以GET或POST方式,檢查註冊使用者名稱是否在資料庫中已存在

Ajax案例-基於HTML,以GET或POST方式,檢查註冊使用者名稱是否在資料庫中已存在

08_register.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>基於HTML,以GET或POST方式,檢查註冊使用者名稱是否在資料庫中已存在</title>
  </head>
  <body>
    
    <form>
        使用者名稱[GET]:
<input id="usernameID" type="text" name="username" maxlength="4"/> 游標移出後,立即檢查結果 </form> <hr/> <span id="resID"></span> <script type="text/javascript"> //建立AJAX非同步物件,即XMLHttpRequest function createAJAX(){ var
ajax = null; try{ ajax = new ActiveXObject("microsoft.xmlhttp"); }catch(e1){ try{ ajax = new XMLHttpRequest(); }catch(e2){ alert("你的瀏覽器不支援ajax,請更換瀏覽器"); } }
return ajax; } </script> <script type="text/javascript"> //定位文字框,同時提供焦點失去事件 document.getElementById("usernameID").onblur = function(){ //獲取文字框中輸入的值 var username = this.value; //如果使用者沒有填內容 if(username.length == 0){ //提示 document.getElementById("resID").innerHTML = "使用者名稱必填"; }else{ //對漢字進行UTF-8(U8)的編碼 username = encodeURI(username); //NO1) var ajax = createAJAX(); //NO2) var method = "GET"; var url = "${pageContext.request.contextPath}/UserServlet?time="+new Date().getTime()+"&username=" + username; ajax.open(method,url); //NO3) ajax.send(null); //--------------------------------------------------------等待 //NO4) ajax.onreadystatechange = function(){ if(ajax.readyState == 4){ if(ajax.status == 200){ //NO5) var tip = ajax.responseText; //NO6) document.getElementById("resID").innerHTML = tip; } } } } } </script> </body> </html>

 

09_register.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>基於HTML,以GET或POST方式,檢查註冊使用者名稱是否在資料庫中已存在</title>
    <!-- 引入外部js文字 -->
    <script type="text/javascript" src="js/ajax.js"></script>
  </head>
  <body>
    
    
    使用者名稱[POST]:<input id="usernameID" type="text" maxlength="4"/>
    <span id="resID">
        <!-- 
        <img src="tip變數" width="12px" height="12px"/>
        -->
    </span>
    
    
    <hr/>

    
    <script type="text/javascript">
        document.getElementById("usernameID").onblur = function(){
            var username = this.value;//傑克
            //NO1)
            var ajax = createAJAX();
            //NO2)
            var method = "POST";
            var url = "${pageContext.request.contextPath}/UserServlet?time="+new Date().getTime();
            ajax.open(method,url);
            //設定AJAX請求頭為POST,他會將請求體中的漢字自動進行UTF-8的編碼
            ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
            //NO3)
            var content = "username=" + username;
            ajax.send(content);
            
            
            //===========================================等待
            
            
            //NO4)
            ajax.onreadystatechange = function(){
                if(ajax.readyState == 4){
                    if(ajax.status == 200){
                        //NO5)
                        var tip = ajax.responseText;
                    
                        //NO6)
                        //建立img標籤
                        var imgElement = document.createElement("img");
                        //設定img標籤的src/width/height的屬性值
                        imgElement.src = tip;
                        imgElement.style.width = "12px";
                        imgElement.style.height = "12px";
                        //定位span標籤
                        var spanElement = document.getElementById("resID");
                        //清空span標籤中的內容
                        spanElement.innerHTML = "";
                        //將img標籤加入到span標籤中
                        spanElement.appendChild(imgElement);
                    }
                }
            }
        }
    </script>
    
    
    <!-- 
    <form action="" method="" enctype="application/x-www-form-urlencoded"></form>
    -->

  </body>
</html>
package loaderman.user;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 基於HTML,以GET或POST方式,檢查註冊使用者名稱是否在資料庫中已存在
 */
public class UserServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        String username = request.getParameter("username");
        byte[] buf = username.getBytes("ISO8859-1");
        username = new String(buf,"UTF-8");
        System.out.println("username=" + username);
        String tip = "<font color='green'>可以註冊</font>";
        if("傑克".equals(username)){
            tip = "<font color='red'>該使用者已存在</font>";
        }
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(tip);
        pw.flush();
        pw.close();
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        System.out.println("username=" + username);

        String tip = "images/MsgSent.gif";
        if("傑克".equals(username)){
            tip = "images/MsgError.gif";
        }
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(tip);
        pw.flush();
        pw.close();
    }
}