fetch 如何實(shí)現(xiàn)請求數(shù)據(jù)
一 序言
在 傳統(tǒng)Ajax 時(shí)代,進(jìn)行 API 等網(wǎng)絡(luò)請求都是通過XMLHttpRequest或者封裝后的框架進(jìn)行網(wǎng)絡(luò)請求,然而配置和調(diào)用方式非?;靵y,對于剛?cè)腴T的新手并不友好。今天我們介紹的Fetch提供了一個(gè)更好的替代方法,它不僅提供了一種簡單,合乎邏輯的方式來跨網(wǎng)絡(luò)異步獲取資源,而且可以很容易地被其他技術(shù)使用,例如 Service Workers。

二 與Ajax對比
使用Ajax請求一個(gè) 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è)務(wù)邏輯更清晰明了,使得代碼易于維護(hù),可讀性更高。
總而言之,F(xiàn)etch 優(yōu)點(diǎn)主要有:
1. 語法簡潔,更加語義化,業(yè)務(wù)邏輯更清晰
2. 基于標(biāo)準(zhǔn) Promise 實(shí)現(xiàn),支持 async/await
3. 同構(gòu)方便,使用isomorphic-fetch
三 Promise簡介
由于 Fetch API 是基于 Promise 設(shè)計(jì),接下來我們簡單介紹下Promise工作流程,方便大家更好理解Fetch。

fetch方法返回一個(gè)Promise對象, 根據(jù) Promise Api 的特性, fetch可以方便地使用then方法將各個(gè)處理邏輯串起來, 使用 Promise.resolve() 或 Promise.reject() 方法將分別返會(huì)肯定結(jié)果的Promise或否定結(jié)果的Promise, 從而調(diào)用下一個(gè)then 或者 catch。一旦then中的語句出現(xiàn)錯(cuò)誤, 也將跳到catch中。
四 請求常見數(shù)據(jù)格式
接下來將介紹如何使用fetch請求本地文本數(shù)據(jù),請求本地JSON數(shù)據(jù)以及請求網(wǎng)絡(luò)接口。其實(shí)操作相比與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)絡(luò)接口</button> <br><br> <div id="output"></div> </div> <script src="app.js"></script>
1.fetch請求本地文本數(shù)據(jù)
本地有一個(gè)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ù)
本地有個(gè)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)絡(luò)接口
獲取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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JS計(jì)算兩個(gè)時(shí)間相差分鐘數(shù)的方法示例
這篇文章主要介紹了JS計(jì)算兩個(gè)時(shí)間相差分鐘數(shù)的方法,結(jié)合完整實(shí)例形式分析了javascript針對日期時(shí)間的轉(zhuǎn)換與計(jì)算相關(guān)操作技巧,需要的朋友可以參考下2018-01-01
csdn 博客中實(shí)現(xiàn)運(yùn)行代碼功能實(shí)現(xiàn)
有時(shí)候因?yàn)閏sdn的博客經(jīng)常處理一些字符,導(dǎo)致代碼很多情況下,都不能正常運(yùn)行,給大家的閱讀帶來了麻煩,下面是腳本之家編輯簡單的整理下。2009-08-08
JavaScript中的ParseInt("08")和“09”返回0的原因分析及解決辦法
這篇文章主要介紹了JavaScript中ParseInt("08")和“09”返回0的原因分析及解決辦法的相關(guān)資料,需要的朋友可以參考下2016-05-05
用javascript代替marquee的滾動(dòng)字幕效果代碼
用javascript代替marquee的滾動(dòng)字幕效果代碼...2007-04-04
electron實(shí)現(xiàn)qq快捷登錄的方法示例
這篇文章主要介紹了electron實(shí)現(xiàn)qq快捷登錄的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-10-10
JS操作字符串轉(zhuǎn)換為數(shù)值并取整的代碼
這篇文章主要介紹了JS操作字符串轉(zhuǎn)換為數(shù)值并取整的代碼,代碼比較短,需要的朋友可以參考下2014-01-01

