網頁中使用傳統方法實現非同步校正詳解

來源:互聯網
上載者:User

標籤:網頁中使用傳統方法實現非同步校正詳解

        學習JavaScript非同步校正時往往是從最傳統的XMLHttpRequest學起,今天星期六,我來談一下對傳統校正的認識:

        代碼1——index.jsp檔案:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>如何使用傳統方法非同步驗證使用者名稱的唯一性</title><script type="text/javascript">function goDemo(pageName){        window.location.href='<%=basePath%>'+pageName;    }</script></head>  <body>    <center style="margin-top: 10%"><font style="color: red;font-size: 18pt;font-weight: bold;">如何使用傳統方法非同步驗證使用者名稱的唯一性</font></center><br>  例子一:<input type="button" value="例子一" onclick="goDemo('demo1.jsp');"/><br><br>  例子二:<input type="button" value="例子二" onclick="goDemo('demo2.jsp');"/><br><br>  例子一與例子二的區別:兩者都實現了使用傳統方法非同步驗證使用者名稱的唯一性的功能,區別在於使用的servlet中的的方法不同:"例子一"使用的servlet中的doGet方法;"例子二"使用的servlet中的doPost方法。</body></html>

        代碼2——demo1.jsp檔案:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>使用的servlet中的doGet方法</title><script type="text/javascript">        function checkUserName(){      var value=document.getElementById("userName").value;      if(value==""){      document.getElementById("showUserName").innerHTML="<font size=\"2\" color=red>使用者名稱不可為空!!!</font>";      }else{          var xmlHttpRequest = null;    if(window.XMLHttpRequest){/*適用於IE7以上(包括IE7)的IE瀏覽器、Firefox瀏覽器、Google瀏覽器和Opera瀏覽器*/    xmlHttpRequest = new XMLHttpRequest();//建立XMLHttpRequest    }else if(window.ActiveXObject){/*適用於IE6.0以下(包括IE6.0)的IE瀏覽器*/    xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");    }//第一步:建立XMLHttpRequest對象,請求未初始化    xmlHttpRequest.onreadystatechange = function (){//readyState值發生改變時XMLHttpRequest對象激發一個readystatechange事件,進而調用後面的函數    if(xmlHttpRequest.readyState==1){       xmlHttpRequest.send();//第三步:發送請求,也可以為xmlHttpRequest.send(null)    }        if(xmlHttpRequest.readyState==2){        console.log("send()方法已執行,請求已發送到伺服器端,但是用戶端還沒有收到伺服器端的響應。");       }    if(xmlHttpRequest.readyState==3){       console.log("已經接收到HTTP回應標頭部資訊,但是訊息體部分還沒有完全接收結束。");       }        if(xmlHttpRequest.readyState==4){//用戶端接收伺服器端資訊完畢。第四步:處理伺服器端發回來的響應資訊        if(xmlHttpRequest.status==200){//與Servlet成功互動        console.log("用戶端已完全接收伺服器端的處理響應。");                var responseValue=xmlHttpRequest.responseText;                if(responseValue==1){               document.getElementById("showUserName").innerHTML="<font size=\"2\" color=\"red\">  使用者名稱已被使用!</font>";            }else if(responseValue==2){                document.getElementById("showUserName").innerHTML="<font size=\"2\" color=\"green\">  使用者名稱有效!!!</font>";        }            }else{//與Servlet互動出現問題            document.getElementById("showUserName").innerHTML="<font size=\"2\" color=\"red\">請求發送失敗!</font>";            }            }           };                      if(xmlHttpRequest.readyState==0){       xmlHttpRequest.open("get","<%=basePath%>AjaxCheckUserNameServlet?userName="+value,true);//第二步:完成請求初始化,提出請求。open方法中的三個參數分別是:請求方式、路徑、是否非同步(true表示非同步,false表示同步)        }     }      }</script>  </head>  <body>   <center style="margin-top: 10%"><font style="color: red;font-size: 18pt;font-weight: bold;">使用的servlet中的doGet方法</font><br><br>          使用者名稱:<input type="text" id="userName" name="userName" size="27" onblur="checkUserName();">  <font size="2" id="showUserName">  *使用者名稱必填,具有唯一性。</font>  </center></body></html>

        代碼3——demo2.jsp檔案:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head>    <title>使用的servlet中的doPost方法</title><script type="text/javascript">function checkUserName(){      var value=document.getElementById("userName").value;      if(value==""){      document.getElementById("showUserName").innerHTML="<font size=\"2\" color=red>使用者名稱不可為空!!!</font>";      }else{          var xmlHttpRequest = null;    if(window.XMLHttpRequest){/*適用於IE7以上(包括IE7)的IE瀏覽器、Firefox瀏覽器、Google瀏覽器和Opera瀏覽器*/    xmlHttpRequest = new XMLHttpRequest();//建立XMLHttpRequest    }else if(window.ActiveXObject){/*適用於IE6.0以下(包括IE6.0)的IE瀏覽器*/    xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");    }//第一步:建立XMLHttpRequest對象,請求未初始化    xmlHttpRequest.onreadystatechange = function (){//readyState值發生改變時XMLHttpRequest對象激發一個readystatechange事件,進而調用後面的函數    if(xmlHttpRequest.readyState==1){       xmlHttpRequest.send();//第三步:發送請求,也可以為xmlHttpRequest.send(null)    }        if(xmlHttpRequest.readyState==2){        console.log("send()方法已執行,請求已發送到伺服器端,但是用戶端還沒有收到伺服器端的響應。");       }    if(xmlHttpRequest.readyState==3){       console.log("已經接收到HTTP回應標頭部資訊,但是訊息體部分還沒有完全接收結束。");       }        if(xmlHttpRequest.readyState==4){//用戶端接收伺服器端資訊完畢。第四步:處理伺服器端發回來的響應資訊        if(xmlHttpRequest.status==200){//與Servlet成功互動        console.log("用戶端已完全接收伺服器端的處理響應。");                var responseValue=xmlHttpRequest.responseText;                if(responseValue==1){               document.getElementById("showUserName").innerHTML="<font size=\"2\" color=\"red\">  使用者名稱已被使用!</font>";            }else if(responseValue==2){                document.getElementById("showUserName").innerHTML="<font size=\"2\" color=\"green\">  使用者名稱有效!!!</font>";        }            }else{//與Servlet互動出現問題            document.getElementById("showUserName").innerHTML="<font size=\"2\" color=\"red\">請求發送失敗!</font>";            }            }           };                      if(xmlHttpRequest.readyState==0){       xmlHttpRequest.open("post","<%=basePath%>AjaxCheckUserNameServlet?userName="+value,true);//第二步:完成請求初始化,提出請求。open方法中的三個參數分別是:請求方式、路徑、是否非同步(true表示非同步,false表示同步)        }     }}</script></head>    <body>   <center style="margin-top: 10%"><font color="red" size="5"><strong>使用的servlet中的doPost方法</strong></font><br><br>          使用者名稱:<input type="text" id="userName" name="userName" size="27" onblur="checkUserName()">  <font size=2 id="showUserName">  *使用者名稱必填,具有唯一性。</font>  </center></body></html>

        代碼4——AjaxCheckUserNameServlet.java檔案:

package com.ghj.packagofserlet;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;public class AjaxCheckUserNameServlet extends HttpServlet {private static final long serialVersionUID = 6387744976765210524L;/** * 處理demo1.jsp中非同步驗證 *  * @author GaoHuanjie */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {try{response.setCharacterEncoding("UTF-8");request.setCharacterEncoding("UTF-8");PrintWriter out = response.getWriter();//System.out.println(1/0);//故意出現異常,以檢查demo1.jsp中xmlHttpRequest.status!=200的分支語句是否可用String userName=request.getParameter("userName");//擷取“使用者名稱”System.out.println("處理demo1.jsp中非同步驗證,使用者名稱為:"+userName);if ("admin".equals(userName)) {out.print("1");//“1”表示使用者名稱不可用。 } else {out.print("2");//“2”表示使用者名稱可用。}out.flush();out.close();}catch (Exception e) {e.printStackTrace();response.setStatus(405);}}/** * 處理demo2.jsp中非同步驗證 *  * @author GaoHuanjie */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {try{response.setCharacterEncoding("UTF-8");request.setCharacterEncoding("UTF-8");PrintWriter out = response.getWriter();//System.out.println(1/0);//故意出現異常,以檢查demo2.jsp中xmlHttpRequest.status!=200的分支語句是否可用String userName=request.getParameter("userName");//擷取“使用者名稱”System.out.println("處理demo2.jsp中非同步驗證,使用者名稱為:"+userName);if ("admin".equals(userName)) {out.print("1");//“1”表示使用者名稱不可用。} else {out.print("2");//“2”表示使用者名稱可用。}out.flush();out.close();}catch (Exception e) {e.printStackTrace();response.setStatus(405);}}}

        代碼5——web.xml檔案:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"><servlet>    <servlet-name>AjaxCheckUserNameServlet</servlet-name>    <servlet-class>com.ghj.packagofserlet.AjaxCheckUserNameServlet</servlet-class></servlet><servlet-mapping>    <servlet-name>AjaxCheckUserNameServlet</servlet-name>    <url-pattern>/AjaxCheckUserNameServlet</url-pattern></servlet-mapping>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>
        【0分下載資源】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.