AJAX - 服務器響應

onreadystatechange 屬性

readyState 屬性存留 XMLHttpRequest 的狀態。

onreadystatechange 屬性定義當 readyState 發生變化時執行的函數。

status 屬性和 statusText 屬性存有 XMLHttpRequest 對象的狀態。

屬性 描述
onreadystatechange 定義了當 readyState 屬性發生改變時所調用的函數。
readyState

保存了 XMLHttpRequest 的狀態。

  • 0: 請求未初始化
  • 1: 服務器連接已建立
  • 2: 請求已接收
  • 3: 正在處理請求
  • 4: 請求已完成且響應已就緒
status
  • 200: "OK"
  • 403: "Forbidden"
  • 404: "Page not found"

如需完整列表,請訪問 Http 消息參考手冊

statusText 返回狀態文本(例如 "OK" 或 "Not Found")

每當 readyState 發生變化時就會調用 onreadystatechange 函數。

readyState4status200 時,響應就緒:

實例

function loadDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML =
            this.responseText;
       }
    };
    xhttp.open("GET", "ajax_info.txt", true);
    xhttp.send(); 
} 

親自試一試

注釋:onreadystatechange 被觸發五次(0-4),每次 readyState 都發生變化。

使用回調函數

回調函數是一種作為參數被傳遞到另一個函數的函數。

如果您的網站中有多個 AJAX 任務,那么您應該創建一個執行 XMLHttpRequest 對象的函數,以及一個供每個 AJAX 任務的回調函數。

該函數應當包含 URL 以及當響應就緒時調用的函數。

實例

loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);
function loadDoc(url, cFunction) {
  var xhttp;
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      cFunction(this);
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}
function myFunction1(xhttp) {
  // 行動在這里
 } 
function myFunction2(xhttp) {
  // 行動在這里
 } 

親自試一試

服務器響應屬性

屬性 描述
responseText 獲取字符串形式的響應數據
responseXML 獲取 XML 數據形式的響應數據

服務器響應方法

方法 描述
getResponseHeader() 從服務器返回特定的頭部信息
getAllResponseHeaders() 從服務器返回所有頭部信息

responseText 屬性

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

實例

document.getElementById("demo").innerHTML = xhttp.responseText;

親自試一試

responseXML 屬性

XML HttpRequest 對象有一個內建的 XML 解析器。

ResponseXML 屬性以 XML DOM 對象返回服務器響應。

使用此屬性,您可以把響應解析為 XML DOM 對象:

實例

請求文件 music_list.xml,并對響應進行解析:

xmlDoc = xhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (i = 0; i < x.length; i++) {
  txt += x[i].childNodes[0].nodeValue + "<br>";
  }
document.getElementById("demo").innerHTML = txt;
xhttp.open("GET",  "music_list.xml", true);
xhttp.send();

親自試一試

您將在本教程的 DOM 章節學到更多有關 XML DOM 的知識。

getAllResponseHeaders() 方法

getAllResponseHeaders() 方法返回所有來自服務器響應的頭部信息。

實例

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML = this.getAllResponseHeaders();
  }
};

親自試一試

getResponseHeader() 方法

getResponseHeader() 方法返回來自服務器響應的特定頭部信息。

實例

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML = this.getResponseHeader("Last-Modified");
  }
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send(); 

親自試一試