Ajax局部重新整理(使用JS操作)

來源:互聯網
上載者:User

標籤:input   too   java   分數   submit   拋出異常   efi   ajax   asc   

  對於在不使用Ajax的情況下,使用JS來進行局部重新整理,主要有如下的幾步:

    1. 得到XMLHttpRequest

    2. 使用open方法開啟串連

    3. 佈建要求頭資訊

    4. 註冊onreadystatechange事件,並判斷是否請求響應成功(使用readyState和status)

    5. 在請求和響應成功之後,取得伺服器響應的資料,使用responseText

   對於直接使用js來自己編寫,這樣工作複雜,步驟多,我們可以將其進行封裝好。同時還有一種更好的方式,就是使用jquery中的ajax方法。

代碼:

  javascript:

<script type="text/javascript">// 取得XMLHttpRequest對象,這個需要進行瀏覽器的判斷function getXMLHttp() {try {// 絕大多數的瀏覽器return new XMLHttpRequest();} catch (e) {// ie遊覽器的判定// 判斷ie6.0try {return new ActvieXObject("Msxml2.XMLHTTP");} catch (e) {// 判斷ie5.5及其更早的ie遊覽器try {return new ActvieXObject("Microsoft.XMLHTTP");} catch (e) {alert("無法取得XMLHttpRequest");// 拋出異常資訊throw (e);}}}}// 進行ajax操作,此操作必須在頁面載入完成之後,進行操作window.onload = function() {// 第一步:取得username文字框和font標籤的元素對象var userEle = document.getElementById("username");var fontEle = document.getElementById("msg");// 第二部:註冊username文字框失去焦時間點事件userEle.onblur = function() {// 第三部:得到ajax的請求對象var xmlHttp = getXMLHttp();// 第四部:開啟串連,第一個參數表示使用post方式提交;第二個參數表示提交的地址,第三個參數表示開啟串連xmlHttp.open("POST", "<c:url value=‘/AjaxServlet‘/>?method=ifRegister", true);// 第五步:佈建要求頭資訊xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");// 第六步:發送請求xmlHttp.send("username=" + userEle.value);// 第七步:判斷是否請求和響應成功// 並給xmlHttp的onreadystatechange事件註冊監聽xmlHttp.onreadystatechange = function() {if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {// 表示響應成功// 在此處接收ajax的響應內容var text = xmlHttp.responseText;if(text==‘n‘) {// 將提示資訊,寫到頁面font標籤內fontEle.innerHTML = "*此使用者名稱已存在...";}}};};};</script>

  jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>Ajax操作樣本</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"><script type="text/javascript">// 取得XMLHttpRequest對象,這個需要進行瀏覽器的判斷function getXMLHttp() {try {// 絕大多數的瀏覽器return new XMLHttpRequest();} catch (e) {// ie遊覽器的判定// 判斷ie6.0try {return new ActvieXObject("Msxml2.XMLHTTP");} catch (e) {// 判斷ie5.5及其更早的ie遊覽器try {return new ActvieXObject("Microsoft.XMLHTTP");} catch (e) {alert("無法取得XMLHttpRequest");// 拋出異常資訊throw (e);}}}}// 進行ajax操作,此操作必須在頁面載入完成之後,進行操作window.onload = function() {// 第一步:取得username文字框和font標籤的元素對象var userEle = document.getElementById("username");var fontEle = document.getElementById("msg");// 第二部:註冊username文字框失去焦時間點事件userEle.onblur = function() {// 第三部:得到ajax的請求對象var xmlHttp = getXMLHttp();// 第四部:開啟串連,第一個參數表示使用post方式提交;第二個參數表示提交的地址,第三個參數表示開啟串連xmlHttp.open("POST", "<c:url value=‘/AjaxServlet‘/>?method=ifRegister", true);// 第五步:佈建要求頭資訊xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");// 第六步:發送請求xmlHttp.send("username=" + userEle.value);// 第七步:判斷是否請求和響應成功// 並給xmlHttp的onreadystatechange事件註冊監聽xmlHttp.onreadystatechange = function() {if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {// 表示響應成功// 在此處接收ajax的響應內容var text = xmlHttp.responseText;if(text==‘n‘) {// 將提示資訊,寫到頁面font標籤內fontEle.innerHTML = "*此使用者名稱已存在...";}}};};};</script>  </head>    <body>    <div align="center">    <h1>注 冊</h1>    <form action="" method="post">    <table>    <tr>    <td>Username : </td>    <td>    <input type="text" id="username" name="username" value=""/>    </td>    <td>    <font size=‘2px‘ color=‘red‘ id=‘msg‘></font>    </td>    </tr>    <tr>    <td>Password : </td>    <td><input type="password" name="password" value=""/></td>    <td>${msg }</td>    </tr>    <tr>    <td colspan="2" align="center">    <input style="width: 100px; height: 35px;     border-radius:5px; background-color:blue; opacity:0.7"     type="submit" value="Register"/>    </td>    </tr>    </table>    </form>    </div>  </body></html>

  daoservlet層:

package cn.geore.ajax;import java.io.IOException;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import priv.geore.toolutils.web.FirmHttpServlet;public class AjaxServlet extends FirmHttpServlet {private AjaxDao dao = new AjaxDao();/** * ajax非同步請求,判斷使用者名稱是否已經被註冊 *  * @param request * @param response * @throws ServletException * @throws IOException */public void ifRegister(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String username = request.getParameter("username");try {Hero hero = dao.findByName(username);System.out.println(hero);if(hero!=null) {response.getWriter().print("n");}} catch (SQLException e) {throw new RuntimeException(e);}}}package cn.geore.ajax;import java.sql.SQLException;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanHandler;import priv.geore.toolutils.jdbc.FirmQueRunner;public class AjaxDao {private QueryRunner runner = new FirmQueRunner();public Hero findByName(String string) throws SQLException {String sql = "SELECT * FROM hero WHERE heroname=?";return runner.query(sql, new BeanHandler<Hero>(Hero.class), string);}}

  

  photo:

  

  

 

 注意: 

  (1)onreadystatechange 屬性

    onreadystatechange 屬性存有處理伺服器響應的函數。

  (2)readyState 屬性

    readyState 屬性存有伺服器響應的狀態資訊。每當 readyState 改變時,onreadystatechange 函數就會被執行。

readyState 屬性
狀態 描敘
0 請求未初始化(在調用 open() 之前)
1 請求已提出(調用 send() 之前)
2 請求已發送(這裡通常可以從響應得到內容標題部)
3 請求處理中(響應中通常有部分資料可用,但是伺服器還沒有完成響應)
4 請求已完成(可以訪問伺服器響應並使用它)

 

  (3)responseText 屬性

    可以通過 responseText 屬性來取回由伺服器返回的資料。

 

Ajax局部重新整理(使用JS操作)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.