国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > HTML5 > 正文

關于h5中的fetch方法解讀(小結)

2024-09-05 07:22:13
字體:
來源:轉載
供稿:網友

Fetch概念

fetch身為H5中的一個新對象,他的誕生,是為了取代ajax的存在而出現,主要目的僅僅只是為了結合ServiceWorkers,來達到以下優化:

  1. 優化離線體驗
  2. 保持可擴展性

當然如果ServiceWorkers和瀏覽器端的數據庫IndexedDB配合,那么恭喜你,每一個瀏覽器都可以成為一個代理服務器一樣的存在。(然而我并不認為這樣是好事,這樣會使得前端越來越重,走以前c/s架構的老路)

1. 前言

既然是h5的新方法,肯定就有一些比較older的瀏覽器不支持了,對于那些不支持此方法的

瀏覽器就需要額外的添加一個polyfill:

[鏈接]: https://github.com/fis-components/whatwg-fetch

2. 用法

ferch(抓取) :

HTML:

fetch('/users.html') //這里返回的是一個Promise對象,不支持的瀏覽器需要相應的ployfill或通過babel等轉碼器轉碼后在執行    .then(function(response) {    return response.text()})    .then(function(body) {    document.body.innerHTML = body})

JSON : 

fetch('/users.json')    .then(function(response) {    return response.json()})    .then(function(json) {    console.log('parsed json', json)})    .catch(function(ex) {    console.log('parsing failed', ex)})

Response metadata :

fetch('/users.json').then(function(response) {  console.log(response.headers.get('Content-Type'))  console.log(response.headers.get('Date'))  console.log(response.status)  console.log(response.statusText)})

Post form:

var form = document.querySelector('form')fetch('/users', {  method: 'POST',  body: new FormData(form)})

Post JSON:

fetch('/users', {  method: 'POST',  headers: {    'Accept': 'application/json',    'Content-Type': 'application/json'  },  body: JSON.stringify({  //這里是post請求的請求體    name: 'Hubot',    login: 'hubot',  })})

File upload:

var input = document.querySelector('input[type="file"]')var data = new FormData()data.append('file', input.files[0]) //這里獲取選擇的文件內容data.append('user', 'hubot')fetch('/avatars', {  method: 'POST',  body: data})

3. 注意事項

(1)和ajax的不同點:

1. fatch方法抓取數據時不會拋出錯誤即使是404或500錯誤,除非是網絡錯誤或者請求過程中被打斷.但當然有解決方法啦,下面是demonstration:

function checkStatus(response) {  if (response.status >= 200 && response.status < 300) { //判斷響應的狀態碼是否正常    return response //正常返回原響應對象  } else {    var error = new Error(response.statusText) //不正常則拋出一個響應錯誤狀態信息    error.response = response    throw error  }}function parseJSON(response) {  return response.json()}fetch('/users')  .then(checkStatus)  .then(parseJSON)  .then(function(data) {    console.log('request succeeded with JSON response', data)  }).catch(function(error) {    console.log('request failed', error)  })

2.一個很關鍵的問題,fetch方法不會發送cookie,這對于需要保持客戶端和服務器端常連接就很致命了,因為服務器端需要通過cookie來識別某一個session來達到保持會話狀態.要想發送cookie需要修改一下信息:

fetch('/users', {  credentials: 'same-origin'  //同域下發送cookie})fetch('https://segmentfault.com', {  credentials: 'include'     //跨域下發送cookie})

下圖是跨域訪問segment的結果

Additional

如果不出意外的話,請求的url和響應的url是相同的,但是如果像redirect這種操作的話response.url可能就會不一樣.在XHR時,redirect后的response.url可能就不太準確了,需要設置下:response.headers['X-Request-URL'] = request.url適用于( Firefox < 32, Chrome < 37, Safari, or IE.)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 油尖旺区| 阳高县| 巴林左旗| 道孚县| 德令哈市| 颍上县| 安陆市| 云阳县| 双桥区| 自治县| 友谊县| 嘉善县| 宿松县| 绥芬河市| 益阳市| 陆川县| 灵宝市| 荆门市| 莎车县| 惠来县| 怀安县| 永登县| 潜江市| 万年县| 马鞍山市| 景东| 枝江市| 黑水县| 剑川县| 门源| 临西县| 滨海县| 翁牛特旗| 长岭县| 高密市| 禄劝| 东乡族自治县| 惠水县| 保亭| 柳江县| 荔波县|