fetch.js

与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

  • same-origin模式很简单,若是一个请求是跨域的,那么返回一个简单的error,这样确保全部的请求遵照同源策略
  • no-cors模式容许来自CDN的脚本、其余域的图片和其余一些跨域资源,可是首先有个前提条件,就是请求的method只能是"HEAD","GET"或者"POST"
  • cors模式咱们一般用做跨域请求来从第三方提供的API获取数据

Response 也有一个type属性,它的值多是"basic","cors","default","error"或者"opaque";json

  • "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";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

相关文章
相关标签/搜索