fetch.js

与XMLHttpRequest(XHR)类似,fetch()方法允许你发出AJAX请求。区别在于Fetch API使用Promise,因此是一种简洁明了的API,比XMLHttpRequest更加简单易用。

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;

  • same-origin模式很简单,如果一个请求是跨域的,那么返回一个简单的error,这样确保所有的请求遵守同源策略
  • no-cors模式允许来自CDN的脚本、其他域的图片和其他一些跨域资源,但是首先有个前提条件,就是请求的method只能是"HEAD","GET"或者"POST"
  • cors模式我们通常用作跨域请求来从第三方提供的API获取数据

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

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

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。

讽刺的是,当IE浏览器终于微响应实现了progress事件的时候,XMLHttpRequest也走到了尽头。 目前,如果你需要支持IE的话,你需要使用一个polyfill库。

promises介绍: 

这种写法被称为composing promises, 是 promises 的强大能力之一。每一个函数只会在前一个 promise 被调用并且完成回调后调用,并且这个函数会被前一个 promise 的输出调用;

 

posted @ 2017-03-08 15:33  米娜-火箭  阅读(10585)  评论(0编辑  收藏  举报