简单的XMLHttpRequest方案——Fetch

作者: Mellong | 来源:发表于2016-03-22 14:06 被阅读347次

    了解更多,请关注我的微信公众号: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/

    相关文章

      网友评论

        本文标题:简单的XMLHttpRequest方案——Fetch

        本文链接:https://www.haomeiwen.com/subject/kpcllttx.html