h5的fetch方法_扣丁学堂HTML5分享h5中的fetch方法解读
扣丁學堂HTML5分享h5中的fetch方法解讀
2018-07-06 14:43:10
725瀏覽
本篇文章扣丁學堂
Fetch概念:
fetch身為H5中的一個新對象,他的誕生,是為了取代ajax的存在而出現,主要目的僅僅只是為了結合ServiceWorkers,來達到以下優化:
優化離線體驗
保持可擴展性
當然如果ServiceWorkers和瀏覽器端的數據庫IndexedDB配合,那么恭喜你,每一個瀏覽器都可以成為一個代理服務器一樣的存在。(然而我并不認為這樣是好事,這樣會使得前端越來越重,走以前c/s架構的老路)
1、前言
既然是h5的新方法,肯定就有一些比較older的瀏覽器不支持了,對于那些不支持此方法的
瀏覽器就需要額外的添加一個polyfill:
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
})
以上就是扣丁學堂
【關注微信公眾號獲取更多學習資料】
標簽:
扣丁學堂HTML5培訓
h5中的fetch方法解讀
HTML5培訓
HTML5視頻教程
HTML5在線課程
HTML5在線學習
HTML5在線視頻
HTML5從入門到精通
html5基礎教程
總結
以上是生活随笔為你收集整理的h5的fetch方法_扣丁学堂HTML5分享h5中的fetch方法解读的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OSG源码编译
- 下一篇: 2017年html5行业报告,云适配发布