使用JavaScript實(shí)現(xiàn)ajax的實(shí)例代碼

字號(hào):


    實(shí)現(xiàn)ajax之前必須要?jiǎng)?chuàng)建一個(gè) XMLHttpRequest 對(duì)象。這是必須的。那么對(duì)使用js實(shí)現(xiàn)ajax的代碼感興趣的朋友可以參考下本文
    AJAX = Asynchronous JavaScript and XML.
    AJAX 是一種創(chuàng)建快速動(dòng)態(tài)網(wǎng)頁(yè)的技術(shù)。
    AJAX 通過(guò)在后臺(tái)與服務(wù)器交換少量數(shù)據(jù)的方式,允許網(wǎng)頁(yè)進(jìn)行異步更新。這意味著有可能在不重載整個(gè)頁(yè)面的情況下,對(duì)網(wǎng)頁(yè)的一部分進(jìn)行更新。
    實(shí)現(xiàn)ajax之前必須要?jiǎng)?chuàng)建一個(gè) XMLHttpRequest 對(duì)象。如果不支持創(chuàng)建該對(duì)象的瀏覽器,則需要?jiǎng)?chuàng)建 ActiveXObject.具體方法如下:
    var xmlHttp;
    function createxmlHttpRequest()
    {
    if (window.ActiveXObject) {
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if
    (window.XMLHttpRequest)
    {
    xmlHttp=new XMLHttpRequest();
    }
    }
    (1)下面使用上面創(chuàng)建的xmlHttp實(shí)現(xiàn)最簡(jiǎn)單的ajax get請(qǐng)求:
    function doGet(url)
    {
    // 注意在傳參數(shù)值的時(shí)候最好使用encodeURI處理一下,以防出現(xiàn)亂碼
    createxmlHttpRequest();
    xmlHttp.open("GET",url);
    xmlHttp.send(null);
    xmlHttp.onreadystatechange = function()
    {
    if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
    alert('success');
    }
    else
    {
    alert('fail');
    }
    }
    }
    (2)使用上面創(chuàng)建的xmlHttp實(shí)現(xiàn)最簡(jiǎn)單的ajax post請(qǐng)求:
    function doPost(url,data)
    {
    // 注意在傳參數(shù)值的時(shí)候最好使用encodeURI處理一下,以防出現(xiàn)亂碼
    createxmlHttpRequest();
    xmlHttp.open("POST",url);
    xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xmlHttp.send(data);
    xmlHttp.onreadystatechange = function()
    {
    if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
    {
    alert('success');
    }
    else
    {
    alert('fail');
    }
    }
    }
    以上內(nèi)容是小編給大家介紹的JavaScript實(shí)現(xiàn)ajax的實(shí)例代碼,希望對(duì)大家有所幫助