一个隐藏最深的秘密就是AJAX的实现底层的XMLHttpRequest
,这个方法原本并非造出来干这事的。如今有不少优雅的API包装XHR,可是这远远不够。因而有了fetch
API。咱们来看看这个API的基本用法。最新的浏览器都已经支持这个方法了。javascript
XHR对于我来讲太过复杂,用起来大概是这样的:html
// 开始XHR这些 if (window.XMLHttpRequest) { // Mozilla, Safari, ... request = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE try { request = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { try { request = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {} } } // 发送请求. request.open('GET', 'https://davidwalsh.name/ajax-endpoint', true); request.send(null);
固然咱们的JavaScript框架可让咱们愿意去用XHR,可是你看到的只是一个简单的例子。java
fetch
方法能够在window
做用域中找到。第一个参数是你要访问的URL:git
fetch('https://davidwalsh.name/some/url', { method: 'get' }).then(function(response) { }).catch(function(err) { // Error :( });
fetch
会返回一个Promise做为结果:github
// 简单的返回结果处理 fetch('https://davidwalsh.name/some/url').then(function(response) { }).catch(function(err) { // Error :( }); // 更高级的链式处理 fetch('https://davidwalsh.name/some/url').then(function(response) { return //... }).then(function(returnedValue) { // ... }).catch(function(err) { // Error :( });
请求能不能灵活使用就在因而否能灵活的设置请求的头。可使用new Headers()
:ajax
// 建立一个空的Headers实例 var headers = new Headers(); // 添加内容 headers.append('Content-Type', 'text/plain'); headers.append('X-My-Custom-Header', 'CustomValue'); // 检查Headers的值 headers.has('Content-Type'); // true headers.get('Content-Type'); // "text/plain" headers.set('Content-Type', 'application/json'); // 删除一个Header headers.delete('X-My-Custom-Header'); // 添加初始值 var headers = new Headers({ 'Content-Type': 'text/plain', 'X-My-Custom-Header': 'CustomValue' });
你可使用append
, has
, get
, set
和delete
方法来设置请求的头。要使用Request头,须要建立一个Request
实例:json
var request = new Request('https://davidwalsh.name/some-url', { headers: new Headers({ 'Content-Type': 'text/plain' }) }); fetch(request).then(function() { /* handle response */ });
咱们来看看Response
和Request
均可以作什么。api
一个Request
实例表明了一个fetch的请求部分。给fetch 传入一个request你能够发出高级的、定制的请求:promise
一个简单的Request
看起来是这样的:浏览器
var request = new Request('https://davidwalsh.name/users.json', { method: 'POST', mode: 'cors', redirect: 'follow', headers: new Headers({ 'Content-Type': 'text/plain' }) }); // 用起来 fetch(request).then(function() { /* handle response */ });
只有第一个参数,请求的URL,是必须的。一旦Request建立,它全部的属性都是只读的。须要注意的是Request
有一个clone
方法,这个方法在Worker API里使用fetch 的时候颇有用。fetch的简化调用方法:
fetch('https://davidwalsh.name/users.json', { method: 'POST', mode: 'cors', redirect: 'follow', headers: new Headers({ 'Content-Type': 'text/plain' }) }).then(function() { /* handle response */ });
使用fetch的then
方法会得到一个Response
实例。你也能够本身建立一个。
// 在service worker测试的时候 // 使用new Response(BODY, OPTIONS)建立一个response var response = new Response('.....', { ok: false, status: 404, url: '/' }); // The fetch的 `then`会得到一个response实例 fetch('https://davidwalsh.name/') .then(function(responseObj) { console.log('status: ', responseObj.status); });
Response
实例也提供了以下的方法:
假设你有一个请求会返回JSON。
fetch('https://davidwalsh.name/demo/arsenal.json').then(function(response) { // Convert to JSON return response.json(); }).then(function(j) { // Yay, `j` is a JavaScript object console.log(j); });
固然也能够用JSON.parse(jsonString)
,可是json方法更加简单易用。
不是全部的接口都返回JSON格式的数据,因此还要处理一些Text/HTML类型的返回结果。
fetch('/next/page') .then(function(response) { return response.text(); }).then(function(text) { // <!DOCTYPE .... console.log(text); });
若是你想要经过fetch加载一个blob的话,会有一点不一样:
fetch('https://davidwalsh.name/flowers.jpg') .then(function(response) { return response.blob(); }) .then(function(imageBlob) { document.querySelector('img').src = URL.createObjectURL(imageBlob); });
另外一个常常会遇到的状况是使用AJAX提交表单数据。
fetch('https://davidwalsh.name/submit', { method: 'post', body: new FormData(document.getElementById('comment-form')) });
fetch
API很好用,可是如今还不容许取消一个请求。不管如何,有了fetch
以后,咱们能够简单的发出AJAX请求了。更多关于fetch 的内容能够参考Github下他们的repo。