什么是Fetch,它和Ajax比有什么优势?

由来:当我们只需要发送Ajax请求时,需要引入整个jQuery,这是非常不合理的。故随着react和vue框架的兴起,于是便有了fetch来解决这一问题

概念:fetch号称是ajax的替代品,它的API是基于Promise设计的,旧版本的浏览器不支持 Promise,需要使用 polyfill es6-promise

二者举例对比:

// 原生XHR	
var xhr = new XMLHttpRequest();	
xhr.open('GET', url);	
xhr.onreadystatechange = function() {	
    if (xhr.readyState === 4 && xhr.status === 200) {	
        console.log(xhr.responseText) // 从服务器获取数据	
    }	
}	
xhr.send()	
// fetch	
fetch(url).then(response = > {	
    if (response.ok) {	
        response.json()	
    }	
}).then(data = > console.log(data)).	
catch (err = > console.log(err))

Fetch是ajax非常好的一个替代品,很有可能将来会完全代替ajax的地位。

我们使用Fetch来获取数据时,会返回给我们一个Pormise对象

    <script>
        fetch("http://www.abc.cn/test")
            .then(Response => Response.json())
            .then(data => {
                console.log(data);
            })
    </script>

Fetch发送数据

	fetch(url,options)
    <script>
        fetch('http://www.mozotech.cn/bangbang/index/user/login', {
          method: 'post',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: new URLSearchParams([["username", "Lan"],["password", "123456"]]).toString()
        })
        .then(res => {
            console.log(res);
            return res.text();
        })
        .then(data => {
            console.log(data);
        })
    </script>

Cookie传递

fetch发送请求时,不像XHR,因为它默认是不带上Cookie的,如果站点依赖于维护一个用户会话,可能导致未经认证的请求,所以我们需要手动的把Cookie带上,只需加上 credentials: 'include'即可:

    <script>
        fetch('https://www.abc.com/search', {
            method: 'GET',
            credentials: 'include' // 强制加入Cookie
          })
          .then((res)=>{
            return res.text()
          })
          .then((res)=>{
            console.log(res)
          })
    </script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值