最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解JavaScript實(shí)現(xiàn)異步Ajax

 更新時(shí)間:2022年05月31日 10:02:22   作者:springsnow  
本文詳細(xì)講解了JavaScript實(shí)現(xiàn)異步Ajax的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

一、什么是 AJAX ?

AJAX = 異步 JavaScript 和 XML。AJAX 是一種用于創(chuàng)建快速動(dòng)態(tài)網(wǎng)頁(yè)的技術(shù)。

通過(guò)在后臺(tái)與服務(wù)器進(jìn)行少量數(shù)據(jù)交換,AJAX 可以使網(wǎng)頁(yè)實(shí)現(xiàn)異步更新。這意味著可以在不重新加載整個(gè)網(wǎng)頁(yè)的情況下,對(duì)網(wǎng)頁(yè)的某部分進(jìn)行更新。傳統(tǒng)的網(wǎng)頁(yè)(不使用 AJAX)如果需要更新內(nèi)容,必需重載整個(gè)網(wǎng)頁(yè)面。

有很多使用 AJAX 的應(yīng)用程序案例:新浪微博、Google 地圖、開(kāi)心網(wǎng)等等。

1、AJAX是基于現(xiàn)有的Internet標(biāo)準(zhǔn)

AJAX是基于現(xiàn)有的Internet標(biāo)準(zhǔn),并且聯(lián)合使用它們:

  • XMLHttpRequest 對(duì)象 (異步的與服務(wù)器交換數(shù)據(jù))
  • JavaScript/DOM (信息顯示/交互)
  • CSS (給數(shù)據(jù)定義樣式)
  • XML (作為轉(zhuǎn)換數(shù)據(jù)的格式)

注意:AJAX應(yīng)用程序與瀏覽器和平臺(tái)無(wú)關(guān)的!

2、AJAX 工作原理

二、AJAX - 創(chuàng)建 XMLHttpRequest 對(duì)象

1、XMLHttpRequest 對(duì)象

XMLHttpRequest 是 AJAX 的基礎(chǔ)。所有現(xiàn)代瀏覽器均支持 XMLHttpRequest 對(duì)象(IE5 和 IE6 使用 ActiveXObject)。

XMLHttpRequest 用于在后臺(tái)與服務(wù)器交換數(shù)據(jù)。這意味著可以在不重新加載整個(gè)網(wǎng)頁(yè)的情況下,對(duì)網(wǎng)頁(yè)的某部分進(jìn)行更新。

2、創(chuàng)建 XMLHttpRequest 對(duì)象

所有現(xiàn)代瀏覽器(IE7+、Firefox、Chrome、Safari 以及 Opera)均內(nèi)建 XMLHttpRequest 對(duì)象。

創(chuàng)建 XMLHttpRequest 對(duì)象的語(yǔ)法:

variable=new XMLHttpRequest();

老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 對(duì)象:

variable=new ActiveXObject("Microsoft.XMLHTTP");

為了應(yīng)對(duì)所有的現(xiàn)代瀏覽器,包括 IE5 和 IE6,請(qǐng)檢查瀏覽器是否支持 XMLHttpRequest 對(duì)象。如果支持,則創(chuàng)建 XMLHttpRequest 對(duì)象。如果不支持,則創(chuàng)建 ActiveXObject :

var xmlhttp;
if (window.XMLHttpRequest)
{
    //  IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執(zhí)行代碼
    xmlhttp=new XMLHttpRequest();
}
else
{
    // IE6, IE5 瀏覽器執(zhí)行代碼
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

三、向服務(wù)器發(fā)送請(qǐng)求請(qǐng)求

1、向服務(wù)器發(fā)送請(qǐng)求

XMLHttpRequest 對(duì)象用于和服務(wù)器交換數(shù)據(jù)。

如需將請(qǐng)求發(fā)送到服務(wù)器,我們使用 XMLHttpRequest 對(duì)象的 open() 和 send() 方法:

xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();

方法:

open(method,url,async):規(guī)定請(qǐng)求的類型、URL 以及是否異步處理請(qǐng)求。

  • method:請(qǐng)求的類型;GET 或 POST
  • url:文件在服務(wù)器上的位置
  • async:true(異步)或 false(同步)

send(string):將請(qǐng)求發(fā)送到服務(wù)器。string:僅用于 POST 請(qǐng)求

注意:open() 方法的 url 參數(shù)是服務(wù)器上文件的地址:

xmlhttp.open("GET","ajax_test.html",true);

該文件可以是任何類型的文件,比如 .txt 和 .xml,或者服務(wù)器腳本文件,比如 .asp 和 .php (在傳回響應(yīng)之前,能夠在服務(wù)器上執(zhí)行任務(wù))。

2、GET 還是 POST?

與 POST 相比,GET 更簡(jiǎn)單也更快,并且在大部分情況下都能用。

然而,在以下情況中,請(qǐng)使用 POST 請(qǐng)求:

  • 無(wú)法使用緩存文件(更新服務(wù)器上的文件或數(shù)據(jù)庫(kù))
  • 向服務(wù)器發(fā)送大量數(shù)據(jù)(POST 沒(méi)有數(shù)據(jù)量限制)
  • 發(fā)送包含未知字符的用戶輸入時(shí),POST 比 GET 更穩(wěn)定也更可靠

3、GET 請(qǐng)求

一個(gè)簡(jiǎn)單的 GET 請(qǐng)求:

xmlhttp.open("GET","/try/ajax/demo_get.php",true);
xmlhttp.send();

在上面的例子中,您可能得到的是緩存的結(jié)果。

為了避免這種情況,請(qǐng)向 URL 添加一個(gè)唯一的 ID:

xmlhttp.open("GET","/try/ajax/demo_get.php?t=" + Math.random(),true);
xmlhttp.send();

如果您希望通過(guò) GET 方法發(fā)送信息,請(qǐng)向 URL 添加信息:

xmlhttp.open("GET","/try/ajax/demo_get2.php?fname=Henry&lname=Ford",true);
xmlhttp.send();

4、POST 請(qǐng)求

一個(gè)簡(jiǎn)單 POST 請(qǐng)求:

xmlhttp.open("POST","/try/ajax/demo_post.php",true);
xmlhttp.send();

如果需要像 HTML 表單那樣 POST 數(shù)據(jù),請(qǐng)使用 setRequestHeader() 來(lái)添加 HTTP 頭。然后在 send() 方法中規(guī)定您希望發(fā)送的數(shù)據(jù):

xmlhttp.open("POST","/try/ajax/demo_post2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");

5、異步 - True 或 False?

AJAX 指的是異步 JavaScript 和 XML(Asynchronous JavaScript and XML)。

XMLHttpRequest 對(duì)象如果要用于 AJAX 的話,其 open() 方法的 async 參數(shù)必須設(shè)置為 true:

xmlhttp.open("GET","ajax_test.html",true);

對(duì)于 web 開(kāi)發(fā)人員來(lái)說(shuō),發(fā)送異步請(qǐng)求是一個(gè)巨大的進(jìn)步。很多在服務(wù)器執(zhí)行的任務(wù)都相當(dāng)費(fèi)時(shí)。AJAX 出現(xiàn)之前,這可能會(huì)引起應(yīng)用程序掛起或停止。

通過(guò) AJAX,JavaScript 無(wú)需等待服務(wù)器的響應(yīng),而是:

  • 在等待服務(wù)器響應(yīng)時(shí)執(zhí)行其他腳本
  • 當(dāng)響應(yīng)就緒后對(duì)響應(yīng)進(jìn)行處理

當(dāng)使用 async=true 時(shí),請(qǐng)規(guī)定在響應(yīng)處于 onreadystatechange 事件中的就緒狀態(tài)時(shí)執(zhí)行的函數(shù):

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("GET","/try/ajax/ajax_info.txt",true);
xmlhttp.send();

注意:當(dāng)您使用 async=false 時(shí),請(qǐng)不要編寫(xiě) onreadystatechange 函數(shù) - 把代碼放到 send() 語(yǔ)句后面即可:

xmlhttp.open("GET","/try/ajax/ajax_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

四、AJAX - 服務(wù)器 響應(yīng)

如需獲得來(lái)自服務(wù)器的響應(yīng),請(qǐng)使用 XMLHttpRequest 對(duì)象的 responseText 或 responseXML 屬性。

  • responseText:獲得字符串形式的響應(yīng)數(shù)據(jù)。
  • responseXML:獲得 XML 形式的響應(yīng)數(shù)據(jù)。

1、responseText 屬性

如果來(lái)自服務(wù)器的響應(yīng)并非 XML,請(qǐng)使用 responseText 屬性。

responseText 屬性返回字符串形式的響應(yīng),因此您可以這樣使用:

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

2、responseXML 屬性

如果來(lái)自服務(wù)器的響應(yīng)是 XML,而且需要作為 XML 對(duì)象進(jìn)行解析,請(qǐng)使用 responseXML 屬性:

xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
{
    txt=txt + x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("myDiv").innerHTML=txt;

五、AJAX - onreadystatechange 事件

當(dāng)請(qǐng)求被發(fā)送到服務(wù)器時(shí),我們需要執(zhí)行一些基于響應(yīng)的任務(wù)。

每當(dāng) readyState 改變時(shí),就會(huì)觸發(fā) onreadystatechange 事件。

readyState 屬性存有 XMLHttpRequest 的狀態(tài)信息。

1、XMLHttpRequest 對(duì)象的三個(gè)重要的屬性:

1、onreadystatechange:存儲(chǔ)函數(shù)(或函數(shù)名),每當(dāng) readyState 屬性改變時(shí),就會(huì)調(diào)用該函數(shù)。

2、readyState:存有 XMLHttpRequest 的狀態(tài)。從 0 到 4 發(fā)生變化。

  • 0: 請(qǐng)求未初始化
  • 1: 服務(wù)器連接已建立
  • 2: 請(qǐng)求已接收
  • 3: 請(qǐng)求處理中
  • 4: 請(qǐng)求已完成,且響應(yīng)已就緒

3、status:狀態(tài)。200: "OK";404: 未找到頁(yè)面

在 onreadystatechange 事件中,我們規(guī)定當(dāng)服務(wù)器響應(yīng)已做好被處理的準(zhǔn)備時(shí)所執(zhí)行的任務(wù)。

當(dāng) readyState 等于 4 且狀態(tài)為 200 時(shí),表示響應(yīng)已就緒:

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}

注意: onreadystatechange 事件被觸發(fā) 4 次(0 - 4), 分別是: 0-1、1-2、2-3、3-4,對(duì)應(yīng)著 readyState 的每個(gè)變化。

2、使用回調(diào)函數(shù)

回調(diào)函數(shù)是一種以參數(shù)形式傳遞給另一個(gè)函數(shù)的函數(shù)。

如果您的網(wǎng)站上存在多個(gè) AJAX 任務(wù),那么您應(yīng)該為創(chuàng)建 XMLHttpRequest 對(duì)象編寫(xiě)一個(gè)標(biāo)準(zhǔn)的函數(shù),并為每個(gè) AJAX 任務(wù)調(diào)用該函數(shù)。

該函數(shù)調(diào)用應(yīng)該包含 URL 以及發(fā)生 onreadystatechange 事件時(shí)執(zhí)行的任務(wù)(每次調(diào)用可能不盡相同):

function myFunction()
{
    loadXMLDoc("/try/ajax/ajax_info.txt",function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
    });
}

六、javascript 腳本化的HTTP----ajax的基石

1、建XMLHttpRequest對(duì)象

// This is a list of XMLHttpRequest-creation factory functions to try
HTTP._factories = [
    function() { return new XMLHttpRequest(); },
    function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
    function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
];

// When we find a factory that works, store it here.
HTTP._factory = null;

// Create and return a new XMLHttpRequest object.
//
// The first time we're called, try the list of factory functions until
// we find one that returns a non-null value and does not throw an
// exception. Once we find a working factory, remember it for later use.
//
HTTP.newRequest = function() {
    if (HTTP._factory != null) return HTTP._factory();

    for(var i = 0; i < HTTP._factories.length; i++) {
        try {
            var factory = HTTP._factories[i];
            var request = factory();
            if (request != null) {
                HTTP._factory = factory;
                return request;
            }
        }
        catch(e) {
            continue;
        }
    }
    // If we get here, none of the factory candidates succeeded,
    // so throw an exception now and for all future calls.
    HTTP._factory
 = function() {
        throw new Error("XMLHttpRequest not supported");
    }
    HTTP._factory(); // Throw an error
}

2、Get請(qǐng)求

HTTP.get = function(url, callback, options) {
    var request = HTTP.newRequest();
    var n = 0;
    var timer;
    if (options.timeout)
        timer = setTimeout(function() {
                               request.abort();
                               if (options.timeoutHandler)
                                   options.timeoutHandler(url);
                           },
                           options.timeout);

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (timer) clearTimeout(timer);
            if (request.status == 200) {
                callback(HTTP._getResponse(request));
            }
            else {
                if (options.errorHandler)
                    options.errorHandler(request.status,
                                         request.statusText);
                else callback(null);
            }
        }
        else if (options.progressHandler) {
            options.progressHandler(++n);
        }
    }

    var target = url;
    if (options.parameters)
        target += "?" + HTTP.encodeFormData(options.parameters)
    request.open("GET", target);
    request.send(null);
};

1、GET工具

//getText()工具
HTTP.getText = function(url, callback) {
var request = HTTP.newRequest();
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
callback(request.responseText);
}
}


request.open("GET", url);
request.send(null);
}


//getXML()工具
HTTP.getXML = function(url, callback) {
var request = HTTP.newRequest();
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
callback(request.responseXML);
}
}


request.open("GET", url);
request.send(null);
}

3、POST請(qǐng)求

/**
 * Send an HTTP POST request to the specified URL, using the names and values
 * of the properties of the values object as the body of the request.
 * Parse the server's response according to its content type and pass
 * the resulting value to the callback function. If an HTTP error occurs,
 * call the specified errorHandler function, or pass null to the callback
 * if no error handler is specified.
 **/
HTTP.post = function(url, values, callback, errorHandler) {
    var request = HTTP.newRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                callback(HTTP._getResponse(request));
            }
            else {
                if (errorHandler) errorHandler(request.status,
                                               request.statusText);
                else callback(null);
            }
        }
    }

    request.open("POST", url);
    // This header tells the server how to interpret the body of the request.
    request.setRequestHeader("Content-Type",
                             "application/x-www-form-urlencoded");
    // Encode the properties of the values object and send them as
    // the body of the request.
    request.send(HTTP.encodeFormData(values));
};

4、獲取Http頭(包括解析頭部數(shù)據(jù))

HTTP.getHeaders = function(url, callback, errorHandler) {
    var request = HTTP.newRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                callback(HTTP.parseHeaders(request));
            }
            else {
                if (errorHandler) errorHandler(request.status,
                                               request.statusText);
                else callback(null);
            }
        }
    }
    request.open("HEAD", url);
    request.send(null);
};

// Parse the response headers from an XMLHttpRequest object and return
// the header names and values as property names and values of a new object.
HTTP.parseHeaders = function(request) {
    var headerText = request.getAllResponseHeaders();  // Text from the server
    var headers = {}; // This will be our return value
    var ls = /^"s*/;  // Leading space regular expression
    var ts = /"s*$/;  // Trailing space regular expression

    // Break the headers into lines
    var lines = headerText.split(""n");
    // Loop through the lines
    for(var i = 0; i < lines.length; i++) {
        var line = lines[i];
        if (line.length == 0) continue;  // Skip empty lines
        // Split each line at first colon, and trim whitespace away
        var pos = line.indexOf(':');
        var name = line.substring(0, pos).replace(ls, "").replace(ts, "");
        var value = line.substring(pos+1).replace(ls, "").replace(ts, "");
        // Store the header name/value pair in a JavaScript object
        headers[name] = value;
    }
    return headers;
};

5、私有方法

1、獲取表單數(shù)據(jù):

/**
 * Encode the property name/value pairs of an object as if they were from
 * an HTML form, using application/x-www-form-urlencoded format
 */
HTTP.encodeFormData = function(data) {
    var pairs = [];
    var regexp = /%20/g; // A regular expression to match an encoded space

    for(var name in data) {
        var value = data[name].toString();
        // Create a name/value pair, but encode name and value first
        // The global function encodeURIComponent does almost what we want,
        // but it encodes spaces as %20 instead of as "+". We have to
        // fix that with String.replace()
        var pair = encodeURIComponent(name).replace(regexp,"+") + '=' +
            encodeURIComponent(value).replace(regexp,"+");
        pairs.push(pair);
    }

    // Concatenate all the name/value pairs, separating them with &
    return pairs.join('&');
};

2、獲取響應(yīng):

HTTP._getResponse = function(request) {
switch(request.getResponseHeader("Content-Type")) {
case "text/xml":
return request.responseXML;

case "text/json":
case "text/javascript":
case "application/javascript":
case "application/x-javascript":
return eval(request.responseText);

default:
return request.responseText;
}
}

6、使用:

//提交表單,調(diào)用POST方法
var uname = document.getElementById("username");
var usex = document.getElementById("sex");
var formdata = {'username':'tom','sex':'男'};
    HTTP.post("./test.php",formdata, doFun, errorFun);
//請(qǐng)求獲取指定的URL的headers
 HTTP.getHeaders("./a.html", doFun, errorFun);

到此這篇關(guān)于JavaScript實(shí)現(xiàn)異步Ajax的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

庆元县| 武宁县| 塔河县| 大渡口区| 绍兴市| 获嘉县| 三台县| 正安县| 麻栗坡县| 民乐县| 盐山县| 文化| 阿拉善盟| 黎城县| 武清区| 丁青县| 昭苏县| 林周县| 新田县| 新沂市| 庆城县| 唐河县| 友谊县| 海兴县| 梓潼县| 玉田县| 奉节县| 平果县| 涞水县| 阳东县| 花莲市| 新蔡县| 霍林郭勒市| 内丘县| 华容县| 浪卡子县| 鹿泉市| 石台县| 江川县| 化隆| 合肥市|