fetch是新一代XMLHttpRequest的一种替代方案。无需安装其他库。可以在浏览器中直接提供其提供的api轻松与后台进行数据交互。
基本用法:(引入vue文件,复制下方代码)
fetch 不需要额外的安装什么东西,直接就可以使用
<div id="box">
<button @click="handleClick()">click</button>
<ul>
<li v-for="data in datalist" :key="data.filmId">
<img :src="data.poster" :alt="data.name">
<h3>{{data.name}}</h3>
<p>{{data.synopsis}}</p>
</li>
</ul>
</div>
<script type="text/javascript">
new Vue({
el:"#box",
data:{
datalist:[]
},
methods: {
handleClick(){
//fetch get
fetch("json/test.json?name=kerwin&age=100").then(res=>{
// console.log(res.json())
//拿到的是 状态码
// return a.text() // 文本格式
return res.json() //json格式
}).then(res=>{
console.log(res.data.films)
this.datalist = res.data.films
}).catch(err=>{
console.log(err)
})
//post body 安全,
/*
1. form 编码 ,name=kerwin&age=100
2. json 编码 ,"{name:'kerwin',age:100}"
*/
//fetch post -1
// fetch("json/test.json",{
// method:"post",
// headers:{
// "Content‐Type": "application/x‐www‐form‐urlencoded"
// },
// body:"name=kerwin&age=100" //请求体
// }).then(res=>res.json()).then(res=>{
// console.log(res)
// })
//fetch post-2
fetch("json/test.json",{
method:"post",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify({
name:"kerwin",
age:100
}) //请求体
}).then(res=>res.json()).then(res=>{
console.log(res)
})
}
},
})
/*
// post-1
fetch("**",{
credentials:"include",
method:'post',
headers: {
"Content‐Type": "application/x‐www‐form‐urlencoded"
},
body: "name=kerwin&age=100",
}).then(res=>res.json()).then(res=>{console.log(res)});
// post-2
fetch("https://m.vip.com/server.html?rpc&method=pageCache&f=www&_=1563946036520",{
method:'post',
headers: {
"Content‐Type": "application/json"
},
body: JSON.stringify({
name:"kerin",
age:100
})
}).then(res=>res.json()).then(res=>{console.log(res)});
*/
</script>
注意:
1 fetch返回的是promise对象。所以fetch().then()第一个then里返回的并不是真正的数据。而是一个promise,所以我们需要通过链式操作第二个then()来获取真正的数据。
2 fetch发送参数是通过body字段来实现的。body是fetch第二个参数的必选参数之一。params的参数如下
method(String): HTTP请求方法,默认为GET
body(String): HTTP的请求参数
headers(Object): HTTP的请求头,默认为{}
credentials(String): 默认为omit,忽略的意思,也就是不带cookie;还有两个参数,same-origin,意思就是同源请求带cookie;include,表示无论跨域还是同源请求都会带cookie
3 body带的参数是一个序列化以后的字符串。类似 name="coc"&age=30.所以这里我们通过qs库进行了序列化。注意通过cdn引入qs后qs函数应该是Qs,Qs.stringify(data)
2 在vue中的使用:
fetch支持在vue环境中使用。这样通过ajax请求就无需通过安装axios依赖库来实现。
一个简单的fetch请求很简单,代码如下:
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
fetch请求的优点:
1.语法简洁,更加语义化
2.更加底层,提供的API丰富(request, response)
3.脱离了XHR,是ES规范里新的实现方式