小谈Ajax与Fetch

XMLHttpRequest与ActiveXObject

  • 今天测试发现IE5已经实现了对XMLHttpRequest的支持。之前一直认为IE8以下是需要ActiveXObject兼容的。
  • 发现ie9&&ie9--竟然没有同源策略限制?有图有真相:
  • IE10请求截图
    IE10有跨域同源限制
    IE9(IE9--)竟然直接通过了跨域!!!!
  • 来段ajax的原生实现:
  • function ajax(option,callback){
        //option:{ method,url },callback:fn
        var xhr = new XMLHttpRequest();//没有必要兼容,因为ie5都支持的
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                if(xhr.status === 200){
                    callback(xhr.responseText)
                }
            }
        }
        xhr.open(option.method,option.url,true);
        //此处可以设置自定义请求头
        xhr.send();
    }
    ajax({url:'http://127.0.0.1:3000/user/list',method:'get'},function(res){
        console.log(res);
    })

    Ajax与Fetch

共同点:

  • 都是window下的子对象,当然fetch也有其他的接口实现
  • 都是客户端对服务端http请求的机制
  • 都有对请求资源路径,方法,header提供配置的机制

不同点:

  • fetch相比ajax更加强大和灵活(采用promise处理回调)
  • api更加的简便和友好
  • ...

来段Fetch的例子:

function fetchFn(option,callback){
    fetch(option.url,{
        method:option.method,
        //credentials: 'include',
        //mode:'cors',
        headers: {
           'Content-Type': 'application/json'
        }
     }).then(res=>{
        res.json().then(function(data){
            callback(data);
        });
     })
}
fetchFn({url:'http://127.0.0.1:3000/users/list',method:'get'},function(res){
    console.log(res);
})

猜你喜欢

转载自blog.csdn.net/qq_40882724/article/details/82055620
今日推荐