AJAX - 服務器 處理響應

XMLHttpRequest 對象的 onreadystatechange 用來自定義要處理服務器響應的回調(diào)函數(shù)。

httpRequest.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
 document.getElementById("output").innerHTML = this.responseText;
  }
};
測試看看?/?

onreadystatechange 屬性定義當readyState變化時要執(zhí)行的函數(shù)。

readyState 屬性存儲 XMLHttpRequest 對象的當前狀態(tài)。

status 屬性存儲 XMLHttpRequest 對象的狀態(tài)代碼。

statusText 屬性保存 XMLHttpRequest 對象的狀態(tài)文本。

屬性描述
onreadystatechange定義當 readyState 屬性變化時要調(diào)用的函數(shù)
readyState保存 XMLHttpRequest 的狀態(tài):
0:請求未初始化
1:服務器連接建立
2:收到請求
3:處理請求
4:請求完成并且響應準備就緒
status返回請求的狀態(tài)號:
200:“OK”
403:“Forbidden”
404:“Not Found”
有關(guān)完整列表,請訪問HTTP狀態(tài)代碼參考
statusText返回狀態(tài)文本(例如,“OK”或“Not Found”)

服務器響應屬性

下表列出了服務器響應屬性:

屬性描述
responseText以字符串形式返回響應數(shù)據(jù)
responseXML將響應數(shù)據(jù)作為XML數(shù)據(jù)返回

responseText屬性

responseText 屬性以 JavaScript 字符串形式返回服務器響應。

document.getElementById("output").innerHTML = httpRequest.responseText;
測試看看?/?

responseXML屬性

responseXML 屬性將服務器響應作為XMLDocument對象返回。

您可以使用 JavaScript DOM 函數(shù)遍歷XMLDocument 對象。

以下示例請求文件ajax_test.xml并解析響應:

xmlDoc = httpRequest.responseXML;
tag = xmlDoc.getElementsByTagName("author");
for (let i = 0; i < tag.length; i++) {
    txt += tag[i].childNodes[0].nodeValue + "<br>";
}

httpRequest.open("GET", "ajax_test.xml", true);
httpRequest.send();
測試看看?/?

服務器響應方法

下表列出了服務器響應方法:

方法描述
getAllResponseHeaders()返回所有Http頭信息
getResponseHeader()返回特定的Http頭信息

getAllResponseHeaders()方法

getAllResponseHeaders() 方法從服務器響應中返回所有 Http 頭信息。

var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
     document.getElementById("output").innerHTML = this.getAllResponseHeaders();
  }
};
測試看看?/?

getResponseHeader()方法

該getResponseHeader()方法從服務器響應中返回特定的 Http 頭信息。

var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
     document.getElementById("output").innerHTML = this.getResponseHeader("Server");
  }
};
測試看看?/?

多個AJAX實例

如果網(wǎng)站中有多個AJAX任務,則應創(chuàng)建兩個功能:

  • 執(zhí)行XMLHttpRequest對象的函數(shù)

  • 每個AJAX任務都有一個回調(diào)函數(shù)

函數(shù)調(diào)用應包含URL以及響應就緒后要調(diào)用的函數(shù)。

fetchDoc("url-1", myFunc1);
fetchDoc("url-2", myFunc2);
fetchDoc("url-3", myFunc3);

function fetchDoc(url, callback) {
  var httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = function() {
   if (this.readyState === 4 && this.status === 200) {
        callback(this);
    }
  };
  httpRequest.open("GET", url, true);
  httpRequest.send();
}

function myFunc1(httpRequest) {
  // action goes here
}
function myFunc2(httpRequest) {
  // action goes here
}
function myFunc3(httpRequest) {
  // action goes here
}
測試看看?/?

回調(diào)函數(shù)是作為參數(shù)傳遞給另一個函數(shù)的函數(shù)。

丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清