fetch實現(xiàn)請求數(shù)據(jù)的方法-創(chuàng)新互聯(lián)

這篇文章給大家分享的是有關(guān)fetch實現(xiàn)請求數(shù)據(jù)的方法的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

創(chuàng)新互聯(lián)堅持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:網(wǎng)站設(shè)計、成都網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時代的武鄉(xiāng)網(wǎng)站設(shè)計、移動媒體設(shè)計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!

一 序言

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

fetch實現(xiàn)請求數(shù)據(jù)的方法

二 與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è)務(wù)邏輯更清晰明了,使得代碼易于維護(hù),可讀性更高。

總而言之,F(xiàn)etch 優(yōu)點主要有:

1. 語法簡潔,更加語義化,業(yè)務(wù)邏輯更清晰

2. 基于標(biāo)準(zhǔn) Promise 實現(xiàn),支持 async/await

3. 同構(gòu)方便,使用isomorphic-fetch

三 Promise簡介

由于 Fetch API 是基于 Promise 設(shè)計,接下來我們簡單介紹下Promise工作流程,方便大家更好理解Fetch。

fetch實現(xiàn)請求數(shù)據(jù)的方法

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)絡(luò)接口。其實操作相比與Ajax,簡單很多!

//HTML部分
 <div class="container">
 <h2>Fetch Api sandbox</h2>
 <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ù)

本地有一個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)絡(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));
}

感謝各位的閱讀!關(guān)于“fetch實現(xiàn)請求數(shù)據(jù)的方法”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。

分享題目:fetch實現(xiàn)請求數(shù)據(jù)的方法-創(chuàng)新互聯(lián)
分享鏈接:http://bm7419.com/article46/ddhdhg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、域名注冊網(wǎng)站設(shè)計公司、品牌網(wǎng)站設(shè)計電子商務(wù)、網(wǎng)站改版

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站優(yōu)化排名