99热99这里只有精品6国产,亚洲中文字幕在线天天更新,在线观看亚洲精品国产福利片 ,久久久久综合网

歡迎加入QQ討論群258996829
麥子學(xué)院 頭像
蘋果6袋
6
麥子學(xué)院

Javascript學(xué)習(xí)之使用fetch進(jìn)行異步請(qǐng)求詳解

發(fā)布時(shí)間:2017-07-25 16:01  回復(fù):0  查看:3129   最后回復(fù):2017-07-25 16:01  
本文和大家分享的主要是javascript中使用fetch進(jìn)行異步請(qǐng)求相關(guān)內(nèi)容,一起來(lái)看看吧,希望對(duì)大家 學(xué)習(xí)javascript 有所幫助。
  在 AJAX 時(shí)代,進(jìn)行 API 等網(wǎng)絡(luò)請(qǐng)求都是通過(guò) XMLHttpRequest 或者封裝后的框架進(jìn)行網(wǎng)絡(luò)請(qǐng)求。 現(xiàn)在產(chǎn)生的 fetch 框架簡(jiǎn)直就是為了提供更加強(qiáng)大、高效的網(wǎng)絡(luò)請(qǐng)求而生,雖然在目前會(huì)有一點(diǎn)瀏覽器兼容的問(wèn)題,但是當(dāng)我們進(jìn)行一些異步請(qǐng)求時(shí),都可以使用 fetch 進(jìn)行完美的網(wǎng)絡(luò)請(qǐng)求。
  Ajax請(qǐng)求
  普通的Ajax請(qǐng)求,用XHR發(fā)送一個(gè)json請(qǐng)求一般是這樣的:
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url);
  xhr.responseType = 'json';
  xhr.onload = function(){
  console.log(xhr.response);
  };
  xhr.onerror = function(){
  console.log("error")
  }
  xhr.send();
  使用fetch實(shí)現(xiàn)的方式:
  fetch(url).then(function(response){
  return response.json();
  }).then(function(data){
  console.log(data)
  }).catch(function(e){
  console.log("error")
  })
  也可以用async/await的方式
  try{
  let response = await fetch(url);
  let data = await response.json();
  console.log(data);
  } catch(e){
  console.log("error")
  }
  用了await后,寫異步代碼感覺(jué)像同步代碼一樣爽。await后面可以跟Promise對(duì)象,表示等待Promise resolve()才會(huì)繼續(xù)下去執(zhí)行,如果Promise被reject()或拋出異常則會(huì)被外面的try...catch捕獲。
  使用fetch
  fetch的主要優(yōu)點(diǎn)是
  · 語(yǔ)法簡(jiǎn)潔,更加語(yǔ)義化
  · 基于標(biāo)準(zhǔn)的Promise實(shí)現(xiàn),支持async/await
  · 同構(gòu)方便
  但是也有它的不足
  · fetch請(qǐng)求默認(rèn)是不帶cookie的,需要設(shè)置fetch(url, {credentials: 'include'})
  · 服務(wù)器返回400,500這樣的錯(cuò)誤碼時(shí)不會(huì)reject,只有網(wǎng)絡(luò)錯(cuò)誤這些導(dǎo)致請(qǐng)求不能完成時(shí),fetch才會(huì)被reject.
  fetch語(yǔ)法:
  fetch(url, options).then(function(response) {
  // handle HTTP response
  }, function(error) {
  // handle network error
  })
  具體參數(shù)案例:
  //兼容包require('babel-polyfill')require('es6-promise').polyfill()
  import 'whatwg-fetch'
  fetch(url, {
  method: "POST",
  body: JSON.stringify(data),
  headers: {
  "Content-Type": "application/json"
  },
  credentials: "same-origin"
  }).then(function(response) {
  response.status     //=> number 100–599
  response.statusText //=> String
  response.headers    //=> Headers
  response.url        //=> String
  response.text().then(function(responseText) { ... })
  }, function(error) {
  error.message //=> String
  })
  參數(shù)說(shuō)明
  url
  定義要獲取的資源。這可能是:一個(gè) USVString 字符串,包含要獲取資源的 URL。一個(gè) Request 對(duì)象。
  options(可選)
  一個(gè)配置項(xiàng)對(duì)象,包括所有對(duì)請(qǐng)求的設(shè)置??蛇x的參數(shù)有:
  method : 請(qǐng)求使用的方法,如 GET、POST。
  headers : 請(qǐng)求的頭信息,形式為 Headers 對(duì)象或 ByteString。
  body : 請(qǐng)求的 body 信息:可能是一個(gè) Blob、BufferSource、FormData、URLSearchParams 或者 USVString 對(duì)象。注意 GET 或 HEAD 方法的請(qǐng)求不能包含 body 信息。
  mode : 請(qǐng)求的模式,如 cors、 no-cors 或者 same-origin。
  credentials : 請(qǐng)求的 credentials,如 omit、same-origin 或者 include。
  cache : 請(qǐng)求的 cache 模式: default, no-store, reload, no-cache, force-cache, 或者 only-if-cached。
  response
  一個(gè) Promise,resolve 時(shí)回傳 Response 對(duì)象:
  屬性:
  status (number) - HTTP請(qǐng)求結(jié)果參數(shù),在100–599 范圍
  statusText (String) - 服務(wù)器返回的狀態(tài)報(bào)告
  ok (boolean) - 如果返回200表示請(qǐng)求成功則為true
  headers (Headers) - 返回頭部信息,下面詳細(xì)介紹
  url (String) - 請(qǐng)求的地址
  方法:
  text() - 以string的形式生成請(qǐng)求text
  json() - 生成JSON.parse(responseText)的結(jié)果
  blob() - 生成一個(gè)Blob
  arrayBuffer() - 生成一個(gè)ArrayBuffer
  formData() - 生成格式化的數(shù)據(jù),可用于其他的請(qǐng)求
  其他方法:
  clone()
  Response.error()
  Response.redirect()
  response.headers
  has(name) (boolean) - 判斷是否存在該信息頭
  get(name) (String) - 獲取信息頭的數(shù)據(jù)
  getAll(name) (Array) - 獲取所有頭部數(shù)據(jù)
  set(name, value) - 設(shè)置信息頭的參數(shù)
  append(name, value) - 添加header的內(nèi)容
  delete(name) - 刪除header的信息
  forEach(function(value, name){ ... }, [thisContext]) - 循環(huán)讀取header的信息
  使用實(shí)例
  //獲取css里ul的id屬性let uldom = document.getElementById("students");//單獨(dú)創(chuàng)建一個(gè)json文件,獲取地址let url = "data.json";
  function main(){
  fetch(url).then(respone=>{
  return respone.json();
  }).then(students=>{
  let html = ``;
  for(let i=0, l=students.length; i<l; i++){
  let name = students .name;
  let age = students.age;
  html += `  
<li>姓名:${name},年齡:${age}</li>  
`
  }
  uldom.innerHTML = html;
  });
  }
  main();
  結(jié)合await最終代碼
  let uldom = document.getElementById("students");let url = "data.json";
  async function main(){
  let respone = await fetch(url);
  let students = await respone.json();
  let html =``;for(let i=0, l=students.length; i<l; i++){
  let name = students.name;
  let age = students.age;
  html += `
    <li>姓名:${name},年齡:${age}</li>
  `
  }
  uldom.innerHTML = html;
  }
  main();
  data.json文件內(nèi)容如下:
  [
  {"name":"張三","age":"3"},
  {"name":"李萬(wàn)","age":"1"},
  {"name":"王二","age":"4"},
  {"name":"二狗","age":"3"},
  {"name":"狗蛋","age":"5"},
  {"name":"牛娃","age":"7"}
  ]
  運(yùn)行后結(jié)果是:
  姓名:張三,年齡:3
  姓名:李萬(wàn),年齡:1
  姓名:王二,年齡:4
  姓名:二狗,年齡:3
  姓名:狗蛋,年齡:5
  姓名:牛娃,年齡:7


來(lái)源: Helloweba 
您還未登錄,請(qǐng)先登錄

熱門帖子

最新帖子

?