ajax入門級執行個體

來源:互聯網
上載者:User

標籤:nts   判斷   pat   writer   成功   led   參數   gbk   對象   

 AJAX = Asynchronous JavaScript And XML(非同步 JavaScript 及 XML)。

Ajax 由 HTML、JavaScript? 技術、DHTML 和 DOM 組成,這一傑出的方法可以將笨拙的 Web 介面轉化成互動性的 Ajax 應用程式。

今天記下ajax入門級例子,希望和我一樣剛入門的可以看懂。

  在AJAX實際運行當中,對於訪問XMLHttpRequest(XHR)時並不是一次完成的,而是分別經曆了多種狀態後取得的結果,對於這種狀態在AJAX中共有5種,分別是。
  0 - (未初始化)還沒有調用send()方法
  1 - (載入)已調用send()方法,正在發送請求
  2 - (載入完成)send()方法執行完成,
  3 - (互動)正在解析響應內容
  4 - (完成)響應內容解析完成,可以在用戶端調用了
  對於上面的狀態,其中“0”狀態是在定義後自動具有的狀態值,而對於成功訪問的狀態(得到資訊)我們大多數採用“4”進行判斷。

index.jsp代碼如下

 

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%><%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 ‘index.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">    -->        <script>        function test(){            //建立XMLHttpRequest對象            var req;            //IE7以下是第二種方式,7以上和其他瀏覽器,如Firefox是第一種方式建立XMLHttpRequest            if(window.XMLHttpRequest){                req = new XMLHttpRequest();            }else{                req = new ActiveXObject("Msxml2.XMLHTTP");            }             //處理響應             req.onreadystatechange = function(){                 if(4==req.readyState){                     var result = req.responseText;                     document.getElementById("div1").innerHTML = result;                                      }             }                        //發送請求           req.open("get", "servlet/TestAjaxServlet", true);           req.send(null);           alert("heihei");//因為是非同步,所以heihei先出現,三秒鐘之後出現ajax text        }        </script>  </head>    <body>    <div id=div1></div>    <input type = "button" value="測試ajax" onclick="test()"/>  </body></html>

 

然後建立一個servlet,TestAjaxServlet.jsp

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 TestAjaxServlet extends HttpServlet {    /**     * The doGet method of the servlet. <br>     *     * This method is called when a form has its tag value method equals to get.     *      * @param request the request send by the client to the server     * @param response the response send by the server to the client     * @throws ServletException if an error occurred     * @throws IOException if an error occurred     */    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        System.out.println("hello ajax");        try {            Thread.sleep(3000);//三秒鐘之後出現ajax text字樣        } catch (InterruptedException e) {            e.printStackTrace();        }        response.getWriter().println("<h1>ajax test </h1>");    }    /**     * The doPost method of the servlet. <br>     *     * This method is called when a form has its tag value method equals to post.     *      * @param request the request send by the client to the server     * @param response the response send by the server to the client     * @throws ServletException if an error occurred     * @throws IOException if an error occurred     */    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        doGet(request,response);    }}

輸入index.jsp地址,

點擊按鈕

 

 三秒鐘之後出現

 因為是非同步所以,先alert才出現ajax test。ajax預設為非同步,及參數裡面是true.

 

ajax入門級執行個體

聯繫我們

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