Fetch兼容性不好源哩,基于promise,fetch請求默認是不帶cookie的吧黄,需要設置fetch(url,{credentials:'include'})
image.png
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./lib/vue.js"></script>
</head>
<body>
<div id="box">
<!-- fetch 兼容性不好 -->
<button @click = "handleFetch()">ajax-fetch</button>
</div>
<script>
var vm = new Vue({
el:'#box',
data:{},
methods:{
handleFetch(){
fetch("json/test.json?name=xiaoming",{
method:'get', //不寫也為get請求
})
// .then(res=>{
// console.log(res)
// return res.json()
// })
// .then(res=>{
// console.log(res)
// })
.then(res=>res.json())
.then(res=>{
console.log(res)
})
//res.text() 字符串 res.json() json對象
// post請求-1
// fetch("json/test.json",{
// method:'post',
// headers:{
// "Content-Type":"application/x-www-form-urlencoded" //請求頭
// },
// body:'name=xiaoming&age=100'
// }).then(res.json()).then(res=>{console.log(res)})
// post請求-2
// fetch("json/test.json",{
// method:'post',
// headers:{
// "Content-Type":"application/json" //請求頭
// },
// body:JSON.stringify({
// name:"xiaoming",
// age:18
// })
// }).then(res.json()).then(res=>{console.log(res)})
}
}
})
</script>
</body>
</html>