需求: 通过fatch把json文件数据请求回来,
要实现的功能:点击一下button按钮,把数据拿回来,
json文件:
{
"name":"yiyi",
"age":100,
"location":"zhengzhou"
}
get方式:
<body>
<div id="box">
<button @click="handleFetch">ajax-fetchGet</button>
</div>
<script>
new Vue({
el:"#box",
data:{
},
methods:{
handleFetch(){
// console.log("111")
fetch("./test.json")//同域名同端口号下可以省略域名和端口号
.then(res =>{
//此时res拿到的是状态码、响应头、拿不到真正的数据
console.log(res)
//res.json拿到的才是真正的数据
return res.json()
}).then(res=>{
//通过第二个then拿到数据
console.log(res)
}).catch(err=>{
console.log(err)
})
}
}
})
</script>
</body>
简写方式:(箭头函数简写)
handleFetch(){
// console.log("111")
fetch("./test.json")//同域名同端口号下可以省略域名和端口号
.then(res =>res.json())
.then(res=>{
//通过第二个then拿到数据
console.log(res)
}).catch(err=>{
console.log(err)
})
}
结果:
- 成功请求到数据了走then,失败了走catch;
- get方式传参,直接在地址(url路径)上拼接:例如:“?name=yiyi&age=100”
- json格式分两种: json对象,json字符串
post方式:(携带发给后端的数据)
- post请求根据参数格式不同分为两种:表单格式“name=yiyi&age=100”、json字符串格式JSON.parse({name:"yiyi",age:100})
第一种方法:传的参数信息是表单格式:
<body>
<div id="box">
<button @click="handleFetch">ajax-fetchPost</button>
</div>
<script>
new Vue({
el:"#box",
data:{
},
methods:{
handleFetch(){
fetch("./test.json",{
method:"post",
headers:{
"Content-Type":"application/x-www-form-urlencoded"
},
body:"name=yiyi&age=100",
}).then(res =>res.json())
.then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
}
}
})
</script>
</body>
第二种方式:传的参数信息是json字符串格式:
<body>
<div id="box">
<button @click="handleFetch">ajax-fetchPost</button>
</div>
<script>
new Vue({
el:"#box",
data:{
},
methods:{
handleFetch(){
fetch("./test.json",{
method:"post",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify({
name:"yiyi",
age:100
}),
}).then(res =>res.json())
.then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
}
}
})
</script>
</body>