对于ajax请求,咱们不只可使用XMLHTTPrequest,还可使用fetchhtml
在使用ajax时,若是想要使得第二个ajax请求调用第一个ajax请求,就得使用在onreadystatechange中再次指定一个ajax请求,若是再想使用第三个,就得继续判断,这样愈来愈多,代码就会变得愈来愈复杂,这就被称为回调地狱ajax
有什么方法能够解决这个问题呢?就是使用promisejson
promise在ES6(ECMAScript 6.0)中被统一规范,因此新版的浏览器基本都是支持promise写法的跨域
一个标准的promise的写法是这样的数组
new Promise(function(resolve, reject) { if(true) { resolve() }; if(false) { reject() }; })
promise中有三种状态,pending(等待中),resolve(已经完成,获得想要的结果),reject(已经获得,但不是想要的结果)promise
在promise中可使用then方法,来处理对应的状态变化,来对应执行
,而且then的执行结果也会返回一个promise对象,因此能够进行屡次then的使用浏览器
继续来看fetchcookie
fetch('http://example.com/movies.json') .then(function(response) { return response.json(); }) .then(function(myJson) { console.log(myJson); });
一个正常的fetch的格式是这样的,以一个url为参数,返回一个promise的responeseapp
可是这只是一个html响应,并非json对象,因此使用json()将其转变为json对象cors
fetch还能够加上第二个参数init
method: 请求使用的方法,如 GET、POST。
headers: 请求的头信息,形式为 Headers 的对象或包含 ByteString 值的对象字面量。
body: 请求的 body 信息:多是一个 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 对象。注意 GET 或 HEAD 方法的请求不能包含 body 信息。
mode: 请求的模式,如 cors、 no-cors 或者 same-origin。
credentials: 请求的 credentials,如 omit、same-origin 或者 include。为了在当前域名内自动发送 cookie , 必须提供这个选项, 从 Chrome 50 开始, 这个属性也能够接受 FederatedCredential 实例或是一个 PasswordCredential 实例。
cache: 请求的 cache 模式: default 、 no-store 、 reload 、 no-cache 、 force-cache 或者 only-if-cached 。
redirect: 可用的 redirect 模式: follow (自动重定向), error (若是产生重定向将自动终止而且抛出一个错误), 或者 manual (手动处理重定向). 在Chrome中,Chrome 47以前的默认值是 follow,从 Chrome 47开始是 manual。
referrer: 一个 USVString 能够是 no-referrer、client或一个 URL。默认是 client。
referrerPolicy: Specifies the value of the referer HTTP header. May be one of no-referrer、 no-referrer-when-downgrade、 origin、 origin-when-cross-origin、 unsafe-url 。
integrity: 包括请求的 subresource integrity 值(例如:sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)。
fetch请求默认是不加cookie的,除非设置credentials,credentials默认为omit,忽略的意思,也就是不带cookie;还有两个参数,same-origin,意思就是同源请求带cookie;include,表示不管跨域仍是同源请求都会带cookie
返回的response
body中经常使用的方法
一个示例
var myImage = document.querySelector('img'); var myHeaders = new Headers(); myHeaders.append('Content-Type', 'image/jpeg'); var myInit = { method: 'GET', headers: myHeaders, mode: 'cors', cache: 'default' }; var myRequest = new Request('flowers.jpg'); fetch(myRequest,myInit).then(function(response) { ... });
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
https://developer.mozilla.org/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/fetch