简介:
fetch是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。fetch不是ajax的进一步封装,而是原生js。Fetch函数就是原生js,没有使用XMLHttpRequest对象。
(先心疼jQuery一会)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200822171658157.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDM0ODAyOA==,size_16,color_FFFFFF,t_70#pic_center)
步入正题,下面分别用GET请求和POST请求发送请求
1 , fetch,请求本地json文件
<button>点击获取</button>
<script>
var btn = document.querySelector('button')
btn.onclick = function(){
fetch('list.json')
.then(res=>res.json())
.then(res=>{
console.log(res)
})
}
</script>
2, fetch,POST请求
<button>点击</button>
<script>
var btn = document.querySelector('button')
btn.onclick = function(){
fetch('https://www.XXX.com/ajax/echo.php',{
body:"name=mumu&&age=20",
method:"POST",
headers:{
'Content-Type':'application/x-www-form-urlencoded'
}
})
.then(res=>res.text())
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(err)
})
}
</script>