DIV CSS 佈局教程網

XMLHttpRequest 同步與非同步請求解析
編輯:關於JavaScript     

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);
});

使用 timeout 與錯誤處理

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,可避免延遲頁面互動,也能更清楚處理成功、失敗與超時狀態。

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