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

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

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

一、什么是 AJAX ?

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

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

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

1、AJAX是基于現(xiàn)有的Internet標準

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

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

注意:AJAX應用程序與瀏覽器和平臺無關(guān)的!

2、AJAX 工作原理

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

1、XMLHttpRequest 對象

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

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

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

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

創(chuàng)建 XMLHttpRequest 對象的語法:

variable=new XMLHttpRequest();

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

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

為了應對所有的現(xiàn)代瀏覽器,包括 IE5 和 IE6,請檢查瀏覽器是否支持 XMLHttpRequest 對象。如果支持,則創(chuàng)建 XMLHttpRequest 對象。如果不支持,則創(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");
}

三、向服務器發(fā)送請求請求

1、向服務器發(fā)送請求

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

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

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

方法:

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

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

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

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

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

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

2、GET 還是 POST?

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

然而,在以下情況中,請使用 POST 請求:

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

3、GET 請求

一個簡單的 GET 請求:

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

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

為了避免這種情況,請向 URL 添加一個唯一的 ID:

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

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

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

4、POST 請求

一個簡單 POST 請求:

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

如果需要像 HTML 表單那樣 POST 數(shù)據(jù),請使用 setRequestHeader() 來添加 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 對象如果要用于 AJAX 的話,其 open() 方法的 async 參數(shù)必須設置為 true:

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

對于 web 開發(fā)人員來說,發(fā)送異步請求是一個巨大的進步。很多在服務器執(zhí)行的任務都相當費時。AJAX 出現(xiàn)之前,這可能會引起應用程序掛起或停止。

通過 AJAX,JavaScript 無需等待服務器的響應,而是:

  • 在等待服務器響應時執(zhí)行其他腳本
  • 當響應就緒后對響應進行處理

當使用 async=true 時,請規(guī)定在響應處于 onreadystatechange 事件中的就緒狀態(tài)時執(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();

注意:當您使用 async=false 時,請不要編寫 onreadystatechange 函數(shù) - 把代碼放到 send() 語句后面即可:

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

四、AJAX - 服務器 響應

如需獲得來自服務器的響應,請使用 XMLHttpRequest 對象的 responseText 或 responseXML 屬性。

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

1、responseText 屬性

如果來自服務器的響應并非 XML,請使用 responseText 屬性。

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

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

2、responseXML 屬性

如果來自服務器的響應是 XML,而且需要作為 XML 對象進行解析,請使用 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 事件

當請求被發(fā)送到服務器時,我們需要執(zhí)行一些基于響應的任務。

每當 readyState 改變時,就會觸發(fā) onreadystatechange 事件。

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

1、XMLHttpRequest 對象的三個重要的屬性:

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

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

  • 0: 請求未初始化
  • 1: 服務器連接已建立
  • 2: 請求已接收
  • 3: 請求處理中
  • 4: 請求已完成,且響應已就緒

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

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

當 readyState 等于 4 且狀態(tài)為 200 時,表示響應已就緒:

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,對應著 readyState 的每個變化。

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

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

如果您的網(wǎng)站上存在多個 AJAX 任務,那么您應該為創(chuàng)建 XMLHttpRequest 對象編寫一個標準的函數(shù),并為每個 AJAX 任務調(diào)用該函數(shù)。

該函數(shù)調(diào)用應該包含 URL 以及發(fā)生 onreadystatechange 事件時執(zhí)行的任務(每次調(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對象

// 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請求

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請求

/**
 * 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、獲取響應:

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);
//請求獲取指定的URL的headers
 HTTP.getHeaders("./a.html", doFun, errorFun);

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

相關(guān)文章

最新評論

玛多县| 平罗县| 咸阳市| 崇州市| 永善县| 高青县| 右玉县| 大关县| 邢台市| 宜都市| 红桥区| 讷河市| 尼木县| 贵溪市| 榕江县| 千阳县| 确山县| 阳谷县| 榆中县| 徐州市| 通城县| 余江县| 贵南县| 龙口市| 伊通| 都安| 秀山| 西城区| 广德县| 洪雅县| 潼南县| 保山市| 会宁县| 清涧县| 方正县| 运城市| 电白县| 萝北县| 绵阳市| 屏边| 寻甸|