使用JavaScript和jQuery簡單實現Ajax技術

來源:互聯網
上載者:User

標籤:script   cat   sys   相容問題   activex   建立   doget   read   admin   

 Ajax的定義

 Ajax被認為是(Asynchronous JavaScript and XML的縮寫)。 允許瀏覽器與伺服器通訊而無須重新整理當前頁面的技術都被叫做Ajax。

 Ajax的工作原理

 Ajax的核心是JavaScript對象XmlHttpRequest。XmlHttpRequest使您可以使用JavaScript向伺服器提出請求並處理響應,而不阻塞使用者。

一、使用JavaScript實現Ajax技術

1.首先建立一個jsp頁面,匯入js頁面並且建立一個測試按鈕。

<script type="text/javascript" src="ajaxGet.js"></script> <!-- src匯入相應的JavaScript實現Ajax代碼 --></head><body>    <input type="button" id="btn" value="ajax"/> <!-- 測試按鈕 --></body>
2.其中我們在js頁面先需要擷取XmlHttpRequest對象,並且需要處理相容問題
擷取XmlHttpRequest對象function getXMLHttpRequest() {    var xmlHttpReq=null;    if (window.XMLHttpRequest) {//Mozilla 瀏覽器        xmlHttpReq = new XMLHttpRequest();    }else {        if (window.ActiveXObject) {//IE 瀏覽器            try {                xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");            }            catch (e) {                try {//IE 瀏覽器                    xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");                }                catch (e) {                }            }        }    }    return xmlHttpReq;
3.接著在相同頁面下開始寫onload事件(get方法發送資料)
window.onload = function(){      var  btnDom=document.getElementById("btn");    btnDom.onclick = function(){        //ajax步驟        //1        var xhr = getXMLHttpRequest();                //2.監聽響應  如何判斷能夠正確請求和響應        xhr.onreadystatechange = function(){            if(xhr.readyState == 4){  //響應結束                if(xhr.status == 200){ //正確響應                    //接收響應資料                    var data = xhr.responseText;                    alert(data);                }            }        };        //3.開啟串連        /*         * method:  get 或 post         * url:  請求路徑         * async: true(表示非同步,預設) false        */        xhr.open("get","../ajaxGetServlet?age=18&userName=jack",true);        //4.發送資料          xhr.send(null); //使用get請求send發送的資料都為null,且不能省略這一步    };  };
或者使用(post請求//第3第4步驟有區別)
 window.onload = function(){      var  btnDom=document.getElementById("btn");    btnDom.onclick = function(){        //1        var xhr = getXMLHttpRequest();        //2.        xhr.onreadystatechange = function(){            if(xhr.readyState == 4){                if(xhr.status == 200){                    var data = xhr.responseText;                    alert(data);                }            }        };        //3.        xhr.open("post","../ajaxPostServlet",true);        /*         * 4.發送資料         * send()  string或null         *             String類型一般為索引值對  "username=zhangsan"         * get請求 都是send(null)         * post請求要send資料需要佈建要求頭         */        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");        xhr.send("user=admin&age=12");    };  };
其中步驟3的url需要我們建立一個servlet
public class AjaxGetServlet extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        String age = request.getParameter("age");        String userName = request.getParameter("userName");        System.out.println(age+"------"+userName);        //響應資料        response.getWriter().print("hello"); //js中步驟2監聽響應            }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        doGet(request, response);    }}

代碼寫完以後,我們只需要按一下(value="ajax")測試按鈕就可以使用ajax技術實現非同步請求與響應。

二、使用jQuery實現Ajax技術案例:如何使用ajax技術實現使用者註冊時使用者名稱是否被佔用?1.jsp註冊頁面
<script type="text/javascript" src="../js/jquery-1.8.3.js"></script><!-- 匯入jQuery包 --><body>    <h3>jquery 實現 ajax</h3>    <p>使用者名稱:<input id="userName" name="userName"/><span id="msg"></span></p>    <script type="text/javascript" src="jqdemo.js"></script><!-- jqdemo.js使用jquery實現ajax --></body>
2.js頁面(無需手動擷取XmlHttpRequest對象)
$(function(){    $("#userName").blur(function(){        var name = $(this).val();        if(name.trim() == ""){            return;        }        //jquery 實現 ajax        $.ajax({            url:"../jqueryUserName",   //請求的路徑            type:"post", // 請求方式 預設是get            data: {     //要發送的資料                "name":name            },              dataType:"text",  //響應資料的類型            success:function(result){ // 正確響應                if(result == "yes"){                    $("#msg").html("使用者名稱可以使用");                }else{                    $("#msg").html("使用者名稱被佔用");                }            },            error:function(){                alert("請求失敗!");            }        });    });});
3.servlet頁面(擷取使用者名稱比較是否被佔用)
public class JqueryUserName extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        System.out.println("jquery ajax 驗證使用者名稱!");        PrintWriter out = response.getWriter();        String name = request.getParameter("name");        if("ajax".equals(name) || "admin".equals(name) || "jack".equals(name)){            //使用者名稱已被使用            out.print("no");        }else{            out.print("yes");        }    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        doGet(request, response);    }}

 

使用JavaScript和jQuery簡單實現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.