ajxa和axios的區別

1.axios 原理仍是屬於 XMLHttpRequest, 所以須要實現一個ajax。
2.但還會須要一個promise對象來對結果進行處理。
3.ajax實現
var Ajax={ios

get: function(url, fn) {
        // XMLHttpRequest對象用於在後臺與服務器交換數據
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.onreadystatechange = function() {
            // readyState == 4說明請求已完成
            if (xhr.readyState == 4 && xhr.status == 200) {
                // 從服務器得到數據
                fn.call(this, xhr.responseText);
            }
        };
        xhr.send();
    }
}

axios實現
var Axios = {ajax

get: function(url) {
        return new Promise((resolve, reject) => {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.onreadystatechange = function() {
                // readyState == 4說明請求已完成
                if (xhr.readyState == 4 && xhr.status == 200) {
                    // 從服務器得到數據
                    resolve(xhr.responseText)
                }
            };
            xhr.send();
        })
    },
}
相關文章
相關標籤/搜索