與XMLHttpRequest(XHR)類似,fetch()方法允許你發出AJAX請求。區別在於Fetch API使用Promise,因此是一種簡潔明了的API,比XMLHttpRequest更加簡單易用。
fetch("../students.json").then(function(response){ if(response.status!==200){ console.log("存在一個問題,狀態碼為:"+response.status); return; } //檢查響應文本
response.json().then(function(data){ console.log(data); }); }).catch(function(err){ console.log("Fetch錯誤:"+err); })
mode屬性用來決定是否允許跨域請求,以及哪些response屬性可讀。可選的mode屬性值為 same-origin,no-cors(默認)以及 cores;
- same-origin模式很簡單,如果一個請求是跨域的,那么返回一個簡單的error,這樣確保所有的請求遵守同源策略
- no-cors模式允許來自CDN的腳本、其他域的圖片和其他一些跨域資源,但是首先有個前提條件,就是請求的method只能是"HEAD","GET"或者"POST"
- cors模式我們通常用作跨域請求來從第三方提供的API獲取數據
Response 也有一個type屬性,它的值可能是"basic","cors","default","error"或者"opaque";
- "basic": 正常的,同域的請求,包含所有的headers除了"Set-Cookie"和"Set-Cookie2"。
- "cors": Response從一個合法的跨域請求獲得, 一部分header和body 可讀。(限定只能在響應頭中看見“Cache-Control”、“Content-Language”、“Content-Type”、“Expires”、“Last-Modified”以及“Progma”)
- "error": 網絡錯誤。Response的status是0,Headers是空的並且不可寫。(當Response是從Response.error()中得到時,就是這種類型)
- "opaque": Response從"no-cors"請求了跨域資源。依靠Server端來做限制。(將不能查看數據,也不能查看響應狀態,也就是說我們不能檢查請求成功與否;目前為止不能在頁面腳本中請求其他域中的資源)
function status(response){ if(response.status>=200 && response.status<300){ return Promise.resolve(response); }else{ return Promise.reject(new Error(response.statusText)); } } function json(response){ return response.json(); } fetch("../students.json",{mode:"cors"})//響應類型“cors”,一般為“basic”; .then(status)//可以鏈接方法
.then(json)
.then(function(data){
console.log("請求成功,JSON解析后的響應數據為:",data); })
.then(function(response){
console.log(response.headers.get('Content-Type')); //application/json
console.log(response.headers.get('Date')); //Wed, 08 Mar 2017 06:41:44 GMT
console.log(response.status); //200
console.log(response.statusText); //ok
console.log(response.type); //cors
console.log(response.url); //http://.../students.json })
.catch(function(err){
console.log("Fetch錯誤:"+err);
})
使用POST方法提交頁面中的一些數據:將method屬性值設置為post,並且在body屬性值中設置需要提交的數據;
credentials屬性決定了cookies是否能跨域得到 : "omit"(默認),"same-origin"以及"include";
var url='...'; fetch(url,{ method:"post",//or 'GET' credentials: "same-origin",//or "include","same-origin":只在請求同域中資源時成功,其他請求將被拒絕。
headers:{
"Content-type":"application:/x-www-form-urlencoded:charset=UTF-8"
},
body:"name=lulingniu&age=40"
})
.then(status) .then(json) //JSON進行解析來簡化代碼 .then(function(data){ console.log("請求成功,JSON解析后的響應數據為:",data); }) .catch(function(err){ console.log("Fetch錯誤:"+err); });
瀏覽器支持:
目前Chrome 42+, Opera 29+, 和Firefox 39+都支持Fetch。微軟也考慮在未來的版本中支持Fetch。
諷刺的是,當IE瀏覽器終於微響應實現了progress事件的時候,XMLHttpRequest
也走到了盡頭。 目前,如果你需要支持IE的話,你需要使用一個polyfill庫。
promises介紹:
這種寫法被稱為composing promises, 是 promises 的強大能力之一。每一個函數只會在前一個 promise 被調用並且完成回調后調用,並且這個函數會被前一個 promise 的輸出調用;