DIV CSS 佈局教程網

用 XMLHttpRequest 發送請求的四個標準步驟
編輯:關於JavaScript     

在使用 fetch 之前,XMLHttpRequest(XHR)是前端與伺服器溝通的唯一主力。它的使用可以拆成固定的四步,記住這個順序就不容易出錯。

  1. 建立 XMLHttpRequest 物件
  2. 設定回呼函數(onreadystatechange)
  3. 初始化請求(open)
  4. 發送請求(send)

完整範例

var userName;
var passWord;
var xmlHttpRequest;

// 步驟一:建立 XHR 物件,需相容 IE 的 ActiveX 實作
function createXmlHttpRequest() {
  if (window.ActiveXObject) {
    return new ActiveXObject("Microsoft.XMLHTTP");  // 舊版 IE
  } else if (window.XMLHttpRequest) {
    return new XMLHttpRequest();                    // 標準瀏覽器
  }
}

function onLogin() {
  userName = document.f1.username.value;
  passWord = document.f1.password.value;
  var url = "LoginServlet?username=" + userName + "&password=" + passWord;

  xmlHttpRequest = createXmlHttpRequest();       // 1. 建立物件
  xmlHttpRequest.onreadystatechange = zswFun;    // 2. 設定回呼
  xmlHttpRequest.open("POST", url, true);        // 3. 初始化(true = 非同步)
  xmlHttpRequest.send(null);                     // 4. 發送
}

// 回呼函數
function zswFun() {
  if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
    var b = xmlHttpRequest.responseText;
    if (b == "true") {
      alert("登錄成功!");
    } else {
      alert("登錄失敗!");
    }
  }
}

兩個狀態碼一定要認識

readyState 共有五個階段:

  • 0 UNSENT:尚未呼叫 open()
  • 1 OPENED:open() 已呼叫,尚未 send()
  • 2 HEADERS_RECEIVED:已收到回應標頭
  • 3 LOADING:正在接收回應本文
  • 4 DONE:請求完成

status 則是 HTTP 狀態碼,200 代表成功。實務上建議用 status >= 200 && status < 300 判斷,這樣 201、204 等一併涵蓋。

這個範例有兩個必須修正的問題

1. 帳號密碼直接拼進 query string 是嚴重的安全漏洞。密碼會出現在網址列、伺服器存取日誌、瀏覽器歷史與任何中介快取裡。正確做法是把參數放進 send() 的 body:

xmlHttpRequest.open("POST", "LoginServlet", true);
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttpRequest.send("username=" + encodeURIComponent(userName)
                  + "&password=" + encodeURIComponent(passWord));

而且正式環境務必走 HTTPS,否則憑證等於明文傳輸。

2. 回呼必須綁在物件上,不能依賴全域變數。範例把 XHR 存成全域,若同時有多個請求,回呼會互相干擾。建議封裝成函數並用閉包保存各自的請求:

function post(url, data, callback) {
  var xhr = createXmlHttpRequest();
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status >= 200 && xhr.status < 300) callback(null, xhr.responseText);
      else callback(xhr.status);
    }
  };
  xhr.open("POST", url, true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.send(data);
}

今天新專案直接用 fetch() 即可,語法乾淨得多,也能以 Promise / async-await 串接:

fetch("LoginServlet", {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: "username=" + encodeURIComponent(userName)
      + "&password=" + encodeURIComponent(passWord)
}).then(function (r) { return r.text(); })
  .then(function (t) { alert(t === "true" ? "登錄成功!" : "登錄失敗!"); });
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved