fetch请求
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>fetch</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<!-- 引入VUE -->
<script type="text/javascript" src="lib/vue.js"></script>
</head>
<body>
<div id="box">
<button @click="handleClick()">click</button>
</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)
}).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)
})
}
},
})
</script>
</body>
</html>
axios请求
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>fetch</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<!-- 引入VUE -->
<script type="text/javascript" src="lib/vue.js"></script>
<!-- 引入axios -->
<script src="lib/axios.js"></script>
</head>
<body>
<div id="box">
<button @click="handleClick()">axios</button>
</div>
<script type="text/javascript">
new Vue({
el:"#box",
data:{
datalist:[]
},
methods: {
handleClick(){
// get
axios.get("json/test.json?name=kerwin&age=100").then(res=>{
// res.data 才是真正的后端数据
// var res =
console.log(res.data)
})
//post -1- x-www-form-urlencode
axios.post("json/test.json","name=kerwin&age=100").then(res=>{
console.log(res.data)
})
//post -2- application/json
axios.post("json/test.json",{
name:"kerwin",
age:100
}).then(res=>{
console.log(res.data)
})
}
},
})
</script>
</body>
</html>