简介:
fetch是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。fetch不是ajax的进一步封装,而是原生js。Fetch函数就是原生js,没有使用XMLHttpRequest对象。
(先心疼jQuery一会)
步入正题,下面分别用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>