Ajax 的 API -> fetch():javascript
一塊兒學習吧:http://javascript.ruanyifeng.com/bom/ajax.html#toc27html
fetch操做返回Promise對象,babel能夠編譯,一些高版本瀏覽器支持。java
fetch(url).then(function (response) { return response.json(); }).then(function (jsonData) { console.log(jsonData); }).catch(function () { console.log('出錯了'); });
對比XHR寫法ajax
var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'json'; xhr.onload = function() { console.log(xhr.response); }; xhr.onerror = function() { console.log('出錯了'); }; xhr.send();
Fetch API提供如下五個數據流讀取器:json
response.text():返回字符串。跨域
response.json():返回一個JSON對象。數組
response.formData():返回一個FormData對象。瀏覽器
response.blob():返回一個對象。服務器
response.arrayBuffer():返回一個二進制數組。babel
數據流只能讀取一次,一旦讀取,數據流變空,再次讀取會報錯。
可使用response.clone()複製一個副本。
var progress = 0; var contentLength = 0; var getStream = function (reader) { return reader.read().then(function (result) { // 若是數據已經讀取完畢,直接返回 if (result.done) { return; } // 取出本段數據(二進制格式) var chunk = result.value; var text = ''; // 假定數據是UTF-8編碼,前三字節是數據頭, // 並且每一個字符佔據一個字節(即都爲英文字符) for (var i = 3; i < chunk.byteLength; i++) { text += String.fromCharCode(chunk[i]); } // 將本段數據追加到網頁之中 document.getElementById('content').innerHTML += text; // 計算當前進度 progress += chunk.byteLength; console.log(((progress / contentLength) * 100) + '%'); // 遞歸處理下一段數據 return getStream(reader); }; };
fetch():
第一個參數:能夠是url也能夠是Request對象實例。Fetch函數返回一個Promise對象,並將一個response對象傳給回調函數。
第二個參數:是一個option對象,用於配置請求方式,發不發送數據給服務器,採不採用跨域方式:
一、mode:值有,basic正常同域請求,cors在CORS機制下跨域請求,opaque非CORS機制下跨域請求。
二、credentials:是否將cookie發送到服務器端,發送"include"
三、mothod:"POST" "GET"
四、headers:{"Cache-Control":"publice,24*60*60,"}
五、body:要傳到後臺的數據,能夠接受blob、formData、字符串(key1=value1&key2=value2) 包括圖片和文件
Fetch API 引入三個新對象 Headers Request Response 也是構造函數 new Headers() new Request() new Response()
使用方法和FormData對象很像
var content = 'Hello World'; var headers = new Headers(); headers.append("Accept", "application/json"); headers.append("Content-Type", "text/plain"); headers.append("Content-Length", content.length.toString()); headers.append("X-Custom-Header", "ProcessThisImmediately");
reqHeaders = new Headers({ "Content-Type": "text/plain", "Content-Length": content.length.toString(), "X-Custom-Header": "ProcessThisImmediately", });
reqHeaders.has("Content-Type") // true reqHeaders.has("Set-Cookie") // false reqHeaders.set("Content-Type", "text/html") reqHeaders.append("X-Custom-Header", "AnotherValue") reqHeaders.get("Content-Length") // 11 reqHeaders.getAll("X-Custom-Header") // ["ProcessThisImmediately", "AnotherValue"] reqHeaders.delete("X-Custom-Header") reqHeaders.getAll("X-Custom-Header") // []
Headers 能夠配合 Request 或者 Response
var headers = new Headers({ 'Content-Type': 'application/json', 'Cache-Control': 'max-age=3600' }); var response = new Response( JSON.stringify({photos: {photo: []}}), {'status': 200, headers: headers} ); response.json().then(function(json) { insertPhotos(json); });
var headers = new Headers(); headers.append('Accept', 'application/json'); var request = new Request(URL, {headers: headers}); fetch(request).then(function(response) { console.log(response.headers); });
var uploadReq = new Request("/uploadImage", { method: "POST", headers: { "Content-Type": "image/png", }, body: "image data" });
var req = new Request("/index.html"); req.method // "GET" req.url // "http://example.com/index.html"
var req = new Request(URL, {method: 'GET', cache: 'reload'}); fetch(req).then(function(response) { return response.json(); }).then(function(json) { someOperator(json); });
fetch方法返回Response對象實例,它有如下屬性。
status
:整數值,表示狀態碼(好比200)fetch("https://example.com", init) .then(function (response) { // Check that the response is a 200 if (response.status === 200) { alert("Content type: " + response.headers.get('Content-Type')); } });
Request對象和Response對象都有body屬性,表示請求的內容。body屬性多是如下的數據類型: