XMLHttpRequest 可建立同步或非同步請求,差異在於 open 方法的第三個參數 async。理解兩者特性,有助於避免頁面阻塞與錯誤處理問題。
var oReq = new XMLHttpRequest();
oReq.open('GET', 'myFile.txt', false);
oReq.send(null);
console.log(oReq.responseText);
主執行緒中的同步請求會阻塞頁面,造成使用者體驗不佳。現代瀏覽器多不建議在主執行緒使用同步請求。
function loadFile(sURL, fCallback) {
var oReq = new XMLHttpRequest();
oReq.onreadystatechange = function () {
if (oReq.readyState === 4) {
if (oReq.status === 200) {
fCallback.call(oReq);
} else {
console.log('Error', oReq.statusText);
}
}
};
oReq.open('GET', sURL, true);
oReq.send(null);
}
loadFile('message.txt', function () {
alert(this.responseText);
});
var req = new XMLHttpRequest();
req.ontimeout = function () {
console.log('請求超時');
};
req.onerror = function () {
console.log('請求錯誤');
};
req.open('GET', url, true);
req.timeout = 3000;
req.send();
非同步請求搭配回呼函式或 Promise,可避免延遲頁面互動,也能更清楚處理成功、失敗與超時狀態。