最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

一 序言

在 傳統(tǒng)Ajax 時(shí)代,進(jìn)行 API 等網(wǎng)絡(luò)請(qǐng)求都是通過XMLHttpRequest或者封裝后的框架進(jìn)行網(wǎng)絡(luò)請(qǐng)求,然而配置和調(diào)用方式非常混亂,對(duì)于剛?cè)腴T的新手并不友好。今天我們介紹的Fetch提供了一個(gè)更好的替代方法,它不僅提供了一種簡(jiǎn)單,合乎邏輯的方式來跨網(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ì)比來看,fetch代碼精簡(jiǎn)許多,業(yè)務(wù)邏輯更清晰明了,使得代碼易于維護(hù),可讀性更高。

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

1. 語法簡(jiǎn)潔,更加語義化,業(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ì),接下來我們簡(jiǎn)單介紹下Promise工作流程,方便大家更好理解Fetch。

fetch方法返回一個(gè)Promise對(duì)象, 根據(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中。

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

接下來將介紹如何使用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文檔,通過以下代碼就可以獲取其中的數(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請(qǐng)求本地JSON數(shù)據(jù)

本地有個(gè)posts.json數(shù)據(jù),與請(qǐng)求本地文本不同的是,得到數(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請(qǐng)求網(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));
}

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

相關(guān)文章

最新評(píng)論

文水县| 新疆| 海口市| 汉川市| 英山县| 凤凰县| 祁阳县| 南陵县| 南阳市| 温宿县| 蛟河市| 北川| 宜宾市| 新乡县| 青浦区| 三亚市| 碌曲县| 湘潭市| 镇康县| 三河市| 松阳县| 会理县| 海宁市| 桂阳县| 三河市| 海伦市| 怀化市| 南漳县| 龙川县| 广东省| 荣成市| 西昌市| 大荔县| 曲周县| 海伦市| 北安市| 邯郸县| 丁青县| 洪雅县| 山东省| 濮阳市|