fetch 如何實現(xiàn)請求數(shù)據(jù)
一 序言
在 傳統(tǒng)Ajax 時代,進行 API 等網(wǎng)絡請求都是通過XMLHttpRequest或者封裝后的框架進行網(wǎng)絡請求,然而配置和調(diào)用方式非?;靵y,對于剛?cè)腴T的新手并不友好。今天我們介紹的Fetch提供了一個更好的替代方法,它不僅提供了一種簡單,合乎邏輯的方式來跨網(wǎng)絡異步獲取資源,而且可以很容易地被其他技術(shù)使用,例如 Service Workers。
二 與Ajax對比
使用Ajax請求一個 JSON 數(shù)據(jù)一般是這樣:
var xhr = new XMLHttpRequest(); xhr.open('GET', url/file,true); xhr.onreadystatechange = function() { if(xhr.readyState==4){ if(xhr.status==200){ var data=xhr.responseText; console.log(data); } }; xhr.onerror = function() { console.log("Oh, error"); }; xhr.send();
同樣我們使用fetch請求JSON數(shù)據(jù):
fetch(url).then(response => response.json())//解析為可讀數(shù)據(jù) .then(data => console.log(data))//執(zhí)行結(jié)果是 resolve就調(diào)用then方法 .catch(err => console.log("Oh, error", err))//執(zhí)行結(jié)果是 reject就調(diào)用catch方法
從兩者對比來看,fetch代碼精簡許多,業(yè)務邏輯更清晰明了,使得代碼易于維護,可讀性更高。
總而言之,F(xiàn)etch 優(yōu)點主要有:
1. 語法簡潔,更加語義化,業(yè)務邏輯更清晰
2. 基于標準 Promise 實現(xiàn),支持 async/await
3. 同構(gòu)方便,使用isomorphic-fetch
三 Promise簡介
由于 Fetch API 是基于 Promise 設計,接下來我們簡單介紹下Promise工作流程,方便大家更好理解Fetch。
fetch方法返回一個Promise對象, 根據(jù) Promise Api 的特性, fetch可以方便地使用then方法將各個處理邏輯串起來, 使用 Promise.resolve() 或 Promise.reject() 方法將分別返會肯定結(jié)果的Promise或否定結(jié)果的Promise, 從而調(diào)用下一個then 或者 catch。一旦then中的語句出現(xiàn)錯誤, 也將跳到catch中。
四 請求常見數(shù)據(jù)格式
接下來將介紹如何使用fetch請求本地文本數(shù)據(jù),請求本地JSON數(shù)據(jù)以及請求網(wǎng)絡接口。其實操作相比與Ajax,簡單很多!
//HTML部分 <div class="container"> <h1>Fetch Api sandbox</h1> <button id="button1">請求本地文本數(shù)據(jù)</button> <button id="button2">請求本地json數(shù)據(jù)</button> <button id="button3">請求網(wǎng)絡接口</button> <br><br> <div id="output"></div> </div> <script src="app.js"></script>
1.fetch請求本地文本數(shù)據(jù)
本地有一個test.txt文檔,通過以下代碼就可以獲取其中的數(shù)據(jù),并且顯示在頁面上。
document.getElementById('button1').addEventListener('click',getText); function getText(){ fetch("test.txt") .then((res) => res.text())//注意:此處是res.text() .then(data => { console.log(data); document.getElementById('output').innerHTML = data; }) .catch(err => console.log(err)); }
2.fetch請求本地JSON數(shù)據(jù)
本地有個posts.json數(shù)據(jù),與請求本地文本不同的是,得到數(shù)據(jù)后還要用forEach遍歷,最后呈現(xiàn)在頁面上。
document.getElementById('button2').addEventListener('click',getJson); function getJson(){ fetch("posts.json") .then((res) => res.json()) .then(data => { console.log(data); let output = ''; data.forEach((post) => { output += `<li>${post.title}</li>`; }) document.getElementById('output').innerHTML = output; }) .catch(err => console.log(err)); }
3.fetch請求網(wǎng)絡接口
獲取https://api.github.com/users
中的數(shù)據(jù),做法與獲取本地JSON的方法類似,得到數(shù)據(jù)后,同樣要經(jīng)過處理
document.getElementById('button3').addEventListener('click',getExternal); function getExternal(){ // https://api.github.com/users fetch("https://api.github.com/users") .then((res) => res.json()) .then(data => { console.log(data); let output = ''; data.forEach((user) => { output += `<li>${user.login}</li>`; }) document.getElementById('output').innerHTML = output; }) .catch(err => console.log(err)); }
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
javascript實現(xiàn)table單元格點擊展開隱藏效果(實例代碼)
這篇文章主要介紹了javascript實現(xiàn)table單元格點擊展開隱藏效果的實例代碼講解,代碼簡單易懂,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-04-04JS開發(fā)中基本數(shù)據(jù)類型具體有哪幾種
JS的數(shù)據(jù)類型包括基本數(shù)據(jù)類型、復雜數(shù)據(jù)類型和特殊數(shù)據(jù)類型,今天我們主要先講解一下基本數(shù)據(jù)類型。感興趣的朋友一起看看吧2017-10-10Javascript設計模式之觀察者模式的多個實現(xiàn)版本實例
這篇文章主要介紹了Javascript設計模式之觀察者模式的多個實現(xiàn)版本實例,本文給出3種實現(xiàn)版本代碼,同時給出了Jquery實現(xiàn)版本,需要的朋友可以參考下2015-03-03JavaScript列表框listbox全選和反選的實現(xiàn)方法
這篇文章主要介紹了JavaScript列表框listbox全選和反選的實現(xiàn)方法,涉及javascript操作列表框listbox的技巧,非常具有實用價值,需要的朋友可以參考下2015-03-03