1. 程式人生 > >Ajax新玩法fetch API

Ajax新玩法fetch API

sync turn div data ade 原生 統一 基於 blank

目前 Web 異步應用都是基於 XMLHttpRequest/ActiveXObject (IE)實現的, 這些對象不是專門為資源獲取而設計的,因而它們的 API 非常復雜,同時還需要開發者處理兼容性問題。 雖然開發者普遍使用 $.ajax() 這樣的上層包裝,但 Fetch API 意在提供更加方便和一致的原生 API, 同時統一 Web 平臺上的資源獲取行為,包括外鏈腳本、樣式、圖片、AJAX 等。同時Fetch API使用Promise,因此是一種簡潔明了的API,比XMLHttpRequest更加簡單易用。

fetch API 語法

 1  fetch(url)
 2     .then(function
(response) { 3 return response.json(); 4 }) 5 .then(function(data) { 6 console.log(data); 7 }) 8 .catch(function(e) { 9 console.log("Oops, error"); 10 }); 11 //使用 ES6 的 箭頭函數 12 fetch(url) 13 .then(response => response.json()) 14 .then(data => console.log(data))
15 .catch(e => console.log("Oops, error", e)) 16 //使用 async/await 來做最終優化 17 //使用 await 後,寫異步代碼就像寫同步代碼一樣爽。await 後面可以跟 Promise 對象,表示等待 Promise resolve() 才會繼續向下執行,如果 Promise 被 reject() 或拋出異常則會被外面的 try…catch 捕獲。 18 (async function () { 19 try { 20 let response = await fetch(url); 21 let data = response.json();
22 console.log(data); 23 } catch(e) { 24 console.log("Oops, error", e); 25 } 26 })();

GET請求

1   fetch(url, {
2     method: "GET", //默認
3     headers:{
4         "Accept": "application/json, text/plain, */*"
5     }
6 })
7 .then(response => response.json())
8 .then(data => console.log(data))
9 .catch(e => console.log("Oops, error", e))

POST請求

 fetch(url, {
    method: "POST",
    headers: {
        "Accept": "application/json, text/plain, */*",
        "Content-type":"application:/x-www-form-urlencoded; charset=UTF-8"
    },
    body: "name=hzzly&age=22"
})
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))

使用Fetch請求發送憑證

要使用Fetch發送帶有諸如cookie之類的憑證的請求。你可以在選項對象中將credentials屬性值設置為“include”:

  fetch(url,{
    credentials: "include"
})

封裝POST請求

  //將對象拼接成 name=hzzly&age=22 的字符串形式
function params(obj) {
    let result = ‘‘
    for(let item in obj) {
        result += `&${item}=${obj[item]}`
    }
    if(result) {
        result = result.slice(1)
    }
    return result
}

function post(url, paramsObj) {
    let result = fetch(url, {
        methods: ‘POST‘,
        credentials: "include"
        headers: {
            "Accept": "application/json, text/plain, */*",
            "Content-type":"application:/x-www-form-urlencoded; charset=UTF-8"
        },
        body: params(paramsObj)
    })
    return result
}

let obj = {
    name: ‘hzzly‘,
    age: 22
}
post(url, obj)
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(e => console.log("Oops, error", e))

原文 請點擊這裏React 標配的Fetch是什麽?

Ajax新玩法fetch API