AJAX、$.ajax、axios、fetch、superagent

原生AJAX

// 1. 建立鏈接
var xhr = null;
xhr = new XMLHttpRequest()
// 2. 鏈接服務器
xhr.open('get', url, true)
// 3. 發送請求
xhr.send(null);
// 4. 接受請求
xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
        if(xhr.status == 200){
            success(xhr.responseText);
        } else { // fail
            fail && fail(xhr.status);
        }
    }
}
複製代碼
  • 優勢:javascript

    經過異步模式,提高了用戶體驗. 優化了瀏覽器和服務器之間的傳輸,減小沒必要要的數據往返,減小了帶寬佔用.java

    Ajax在客戶端運行,承擔了一部分原本由服務器承擔的工做,減小了大用戶量下的服務器負載。node

    Ajax能夠實現動態不刷新(局部刷新)ios

  • 缺點:ajax

    安全問題 AJAX暴露了與服務器交互的細節。json

    對搜索引擎的支持比較弱。axios

    不容易調試。api

$.ajax

jQuery對Ajax的封裝跨域

$.ajax({
    dataType: 'json', // 設置返回值類型
    contentType: 'application/json', // 設置參數類型
    headers: {'Content-Type','application/json'},// 設置請求頭
    xhrFields: { withCredentials: true }, // 跨域攜帶cookie
    data: JSON.stringify({a: [{b:1, a:1}]}), // 傳遞參數
    error:function(xhr,status){  // 錯誤處理
       console.log(xhr,status);
    },
    success: function (data,status) {  // 獲取結果
       console.log(data,status);
    }
})
複製代碼

$.ajax只接收一個參數,這個參數接收一系列配置promise

Axios

詳細可參考:www.jianshu.com/p/7a9fbcbb1…

axios基於Promise對原生的XHR進行了很是全面的封裝,使用方式也很是的優雅。另外,axios一樣提供了在node環境下的支持,可謂是網絡請求的首選方案。支持全部現代瀏覽器,甚至包括 IE8+!

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
複製代碼
  • 優勢

    同時支持 Node.js 和瀏覽器

    支持 Promise API

    能夠配置或取消請求

    能夠設置響應超時

    支持防止跨站點請求僞造(XSRF)攻擊

    能夠攔截未執行的請求或響應

    支持顯示上傳進度

    普遍用於 React 和 Vue 項目

  • 缺點 用起來比較麻煩

Superagent

改良版 Ajax——與 Node.js HTTP 客戶端搭配使用

Superagent 是一個基於 Promise 的輕量級漸進式 AJAX API,很是適合發送 HTTP 請求以及接收服務器響應。

與 Axios 相同,它既適用於 Node,也適用於全部現代瀏覽器。

用 Superagent 發起 HTTP 請求就像在 request 對象上調用方法同樣簡單:

var superagent = require('superagent');

superagent.post(`${prefix}/payplatform/pay/pay`).withCredentials().send(params).set({'appType': 5, 'blackbox' : blackbox}).then(response => {
    let body = response.body;
    if (body.errno === 0) {
        return body.data;
    } else {
        return Promise.reject(body);
    }
});
複製代碼
  • 優勢

它有一個插件生態,經過構建插件能夠實現更多功能

可配置

HTTP 請求發送接口友好

能夠爲請求鏈式添加方法

適用於瀏覽器和 Node

支持顯示上傳和下載進度

支持分塊傳輸編碼

支持舊風格的回調

繁榮的插件生態,支持衆多常見功能

  • 缺點

其 API 不符合任何標準

Fetch

Fetch 是瀏覽器自帶的用於發送請求的 API,旨在替代 XMLHttpRequest。

使用fetch,你不須要再額外加載一個外部資源。但它尚未被瀏覽器徹底支持,因此你仍然須要一個polyfill。

const options = {
    method: "POST", // 請求參數
    headers: { "Content-Type": "application/json"}, // 設置請求頭
    body: JSON.stringify({name:'123'}), // 請求參數
    credentials: "same-origin", // cookie設置
    mode: "cors", // 跨域
}
fetch('http://www.xxx.com',options).then(function(response) {
    return response.json();
}).then(function(myJson) {
    console.log(myJson); // 響應數據
}).catch(function(err){
    console.log(err); // 異常處理
})
複製代碼
  • 優勢

    靈活易用

    使用 Promise 避免回調地獄

    支持全部現代瀏覽器

    遵循 request-response 方案

    語法簡單清晰

支持 React Native

  • 缺點

    不支持服務器端使用

    缺少開發庫的亮點功能,好比取消請求

    沒有內置默認值,如請求模式,請求頭,請求憑據。

最後 用promise封裝http請求

function getJSON (url) {
    return new Promise( (resolve, reject) => {
        var xhr = new XMLHttpRequest()
        xhr.open('GET', url, true)

        xhr.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    resolve(this.responseText, this)
                } else {
                    var resJson = { code: this.status, response: this.response }
                    reject(resJson, this)
                }
            }
        }

        xhr.send()
    })
}

function postJSON(url, data) {
    return new Promise( (resolve, reject) => {
        var xhr = new XMLHttpRequest()
        xhr.open("POST", url, true)
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        xhr.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    resolve(JSON.parse(this.responseText), this)
                } else {
                    var resJson = { code: this.status, response: this.response }
                    reject(resJson, this)
                }
            }
        }

        xhr.send(JSON.stringify(data))
    })
}
複製代碼
getJSON('/api/v1/xxx').then( value => { 
  // dosomething 
}).catch( error => {
  // dosomething 
})
複製代碼
相關文章
相關標籤/搜索