Web前端之路iOS,object-c和swift开发程序员

简单的XMLHttpRequest方案——Fetch

2016-03-22  本文已影响347人  Mellong

了解更多,请关注我的微信公众号:mellong

本周,新的Fetch标准已经登陆Chrome Canary(version 42)。这是我一直在等待的规格之一。用一个简洁的界面确实简化了XMLHttpRequest,并配有内置保证。

所以,给你一些的认识,这里是你目前怎么写一个XMLHttpRequest:

var req = new XMLHttpRequest();req.onload = function () {  
   console.log(this.responseText);
};
req.open('GET', 'http://someendpoint.com/api/stuff', true);
req.send();

这是一个非常简单的例子,如你所知,它可以在你开始处理错误的情况下得到更多详细的信息。

而现在,这是和window.fetch()进行网络请求一样的,但不一样的是额外增加了错误处理:

window.fetch('http://someendpoint.com/api/stuff').then(function (response) {    
    return reponse.text();
}).then(function (text) {    
    console.log(text);
}).catch(function (e) {    
    console.log(e);
});

在我看了这种写法更简单,而且,这也是定制的:

window.fetch('http://someendpoint.com/api/stuff', {
    method: 'POST',
    headers: {
        'Accept': 'application/json', 
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({ someField: 1234, anotherField: 'foobar' })
}).then(function (response) {
    return reponse.text();
}).then(function (text) {
    console.log(text);
}).catch(function (e) {
    console.log(e);});

看一看这个规范,这里面还有包括更多的特性。

那么其他浏览器支持吗?

Github上发布了一个Fetch polyfill工具,与所有的浏览器工作得很好(IE9+在内),只要确保你也安装es6-promise
polyfill工具来保证支持旧的浏览器。

翻译源文: http://blog.rogeriopvl.com/archives/simple-xmlhttprequests-with-window.fetch/

上一篇 下一篇

猜你喜欢

热点阅读