欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

fetch 如何實(shí)現(xiàn)請(qǐng)求數(shù)據(jù)

 更新時(shí)間:2018年12月20日 11:04:17   作者:浪里行舟  
這篇文章主要介紹了fetch 如何實(shí)現(xiàn)請(qǐng)求數(shù)據(jù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

一 序言

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

二 與Ajax對(duì)比

使用Ajax請(qǐng)求一個(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請(qǐng)求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方法

從兩者對(duì)比來(lái)看,fetch代碼精簡(jiǎn)許多,業(yè)務(wù)邏輯更清晰明了,使得代碼易于維護(hù),可讀性更高。

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

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

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

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

三 Promise簡(jiǎn)介

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

fetch方法返回一個(gè)Promise對(duì)象, 根據(jù) Promise Api 的特性, fetch可以方便地使用then方法將各個(gè)處理邏輯串起來(lái), 使用 Promise.resolve() 或 Promise.reject() 方法將分別返會(huì)肯定結(jié)果的Promise或否定結(jié)果的Promise, 從而調(diào)用下一個(gè)then 或者 catch。一旦then中的語(yǔ)句出現(xiàn)錯(cuò)誤, 也將跳到catch中。

四 請(qǐng)求常見(jiàn)數(shù)據(jù)格式

接下來(lái)將介紹如何使用fetch請(qǐng)求本地文本數(shù)據(jù),請(qǐng)求本地JSON數(shù)據(jù)以及請(qǐng)求網(wǎng)絡(luò)接口。其實(shí)操作相比與Ajax,簡(jiǎn)單很多!

//HTML部分
 <div class="container">
 <h1>Fetch Api sandbox</h1>
 <button id="button1">請(qǐng)求本地文本數(shù)據(jù)</button>
 <button id="button2">請(qǐng)求本地json數(shù)據(jù)</button>
 <button id="button3">請(qǐng)求網(wǎng)絡(luò)接口</button>
 <br><br>
 <div id="output"></div>
 </div>
 <script src="app.js"></script>

1.fetch請(qǐng)求本地文本數(shù)據(jù)

本地有一個(gè)test.txt文檔,通過(guò)以下代碼就可以獲取其中的數(shù)據(jù),并且顯示在頁(yè)面上。

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請(qǐng)求本地JSON數(shù)據(jù)

本地有個(gè)posts.json數(shù)據(jù),與請(qǐng)求本地文本不同的是,得到數(shù)據(jù)后還要用forEach遍歷,最后呈現(xiàn)在頁(yè)面上。

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請(qǐng)求網(wǎng)絡(luò)接口

獲取https://api.github.com/users中的數(shù)據(jù),做法與獲取本地JSON的方法類(lèi)似,得到數(shù)據(jù)后,同樣要經(jīng)過(guò)處理

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));
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論