由来:当我们只需要发送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>