DIV CSS 佈局教程網

深入 JavaScript 的 Ajax:XMLHttpRequest 從建立到收尾的完整流程
編輯:關於JavaScript     

Ajax 不是新語言,而是一套「用既有標準做非同步溝通」的寫法。它讓網頁不必整頁重載,就能在背後跟伺服器要資料、送資料,使用者點一下之後畫面不必刷新,體感自然快得多。

一、核心是 XMLHttpRequest

XHR 提供了一組介面:送出請求、接收回應。整個生命週期可以拆成 open → send → 等待 readyState 變化 → 讀取回應。

var xhr = new XMLHttpRequest(); // 適用 IE7 以上與所有現代瀏覽器

二、open() 與 send()

open() 帶三個參數:請求方法(GET、POST…)、請求的 URL、是否非同步。要注意的是呼叫 open() 並不會真的送出請求,它只是把請求準備好。

xhr.open('get', 'index.jsp', false); // 最後一個 false 代表同步,實務上請用 true

send() 才是真正送出。它的參數是請求主體(body),沒有 body 時必須明確傳入 null,某些舊瀏覽器在省略參數時會出錯。

xhr.send(null);

三、回應有哪些東西

回應回來後,資料會填進 XHR 的屬性:

  • responseText:以文字呈現的回應主體
  • responseXML:當 Content-Type 是 text/xml 或 application/xml 時,可取得 XML 文件物件
  • status:HTTP 狀態碼
  • statusText:狀態碼的文字說明

200~299 代表成功,304 表示資源未變更、可直接使用瀏覽器快取,兩者都算「可用」:

xhr.open('get', 'index.jsp', false);
xhr.send(null);
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
  console.log(xhr.responseText);
} else {
  console.log('請求失敗:' + xhr.status);
}

四、readyState 的五個階段

  • 0:未初始化,尚未呼叫 open()
  • 1:已呼叫 open(),尚未 send()
  • 2:已 send(),尚未收到回應
  • 3:正在接收部分資料
  • 4:全部資料到齊,可以安全使用

每次 readyState 改變都會觸發 readystatechange。實務上只有在 4 的時候才處理資料,而事件處理函式必須在 open() 之前掛上,否則可能漏掉早期階段(這是舊版瀏覽器常見的相容性陷阱)。

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
      console.log(xhr.responseText);
    } else {
      console.log('請求失敗:' + xhr.status);
    }
  }
};
xhr.open('get', 'index.jsp', true);
xhr.send(null);

想在資料到齊前放棄,隨時可以中止:

xhr.abort();

五、HTTP 標頭

送出 XHR 時,瀏覽器會自動帶上 Accept、Accept-Charset、Accept-Encoding、Accept-Language、Connection、Cookie、Host、Referer、User-Agent 等標頭。要加自訂標頭,用 setRequestHeader(),順序必須在 open() 之後、send() 之前:

xhr.open('get', 'index.jsp', true);
xhr.setRequestHeader('MyHeader', 'MyValue');
xhr.send(null);

讀取回應標頭則用 getResponseHeader('名稱');要一次拿全部,用 getAllResponseHeaders(),它會回傳一個包含所有標頭的長字串(需要自己拆行解析)。

var myHeader = xhr.getResponseHeader('MyHeader');
var allHeaders = xhr.getAllResponseHeaders();

六、GET 與 POST 的差異

GET 是查詢用,參數接在 URL 後面。每個參數的名稱與值都必須經過 encodeURIComponent() 編碼,否則遇到 &、=、空白或中文就會出錯:

xhr.open('get', 'login.jsp?name1=' + encodeURIComponent('value1')
                   + '&name2=' + encodeURIComponent('value2'), true);

如果要把多個參數組裝得整齊一點,可以自己寫一個附加函式:

function addURLParam(url, name, value) {
  url += (url.indexOf('?') === -1 ? '?' : '&');
  url += encodeURIComponent(name) + '=' + encodeURIComponent(value);
  return url;
}

var url = 'login.jsp';
url = addURLParam(url, 'username', 'xxyh');
url = addURLParam(url, 'password', 'xxyh123');
xhr.open('get', url, true);

POST 則用來送出需要被保存的資料,body 容量大、格式自由。最傳統的表單式提交要把 Content-Type 設為 application/x-www-form-urlencoded,body 是「key=value&key2=value2」的字串:

xhr.open('post', 'login.jsp', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var form = document.getElementById('user-info');
xhr.send(serialize(form)); // serialize() 需自行實作或引用函式庫

而 serialize() 的精神其實很單純,就是把表單欄位 name/value 配對起來再編碼:

function serialize(form) {
  var parts = [];
  for (var i = 0; i < form.elements.length; i++) {
    var el = form.elements[i];
    if (!el.name || el.disabled) continue;
    if ((el.type === 'checkbox' || el.type === 'radio') && !el.checked) continue;
    parts.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value));
  }
  return parts.join('&');
}

若改成傳送 JSON,只要把 Content-Type 換成 application/json、body 用 JSON.stringify() 序列化,後端就能直接解析,這也是目前主流做法。

結語:直接用 Fetch 也是選項

原生 XHR 的寫法繁瑣,因此 ES 之後有了 Fetch:

fetch('index.jsp')
  .then(function (res) { return res.json(); })
  .then(function (data) { console.log(data); })
  .catch(function (err) { console.log(err.message); });

不過理解 XHR 仍然值得——它說明了狀態碼、標頭、非同步流程這些背後真正在發生的事,而 Fetch、axios、jQuery.ajax 全都是建立在同樣的基礎上。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved