与XMLHttpRequest(XHR)相似,fetch()方法容许你发出AJAX请求。区别在于Fetch API使用Promise,所以是一种简洁明了的API,比XMLHttpRequest更加简单易用。git
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;github
Response 也有一个type属性,它的值多是"basic","cors","default","error"或者"opaque";json
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";promise
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。cookie
讽刺的是,当IE浏览器终于微响应实现了progress事件的时候,XMLHttpRequest
也走到了尽头。 目前,若是你须要支持IE的话,你须要使用一个polyfill库。网络
promises介绍: app
这种写法被称为composing promises, 是 promises 的强大能力之一。每个函数只会在前一个 promise 被调用而且完成回调后调用,而且这个函数会被前一个 promise 的输出调用;cors