一、fetch
首先我们为什么不考虑使用XMLHttpRequest?因为XMLHttpRequest 是一个设计粗糙的 API,配置和调用方式非常混乱,而且基于事件的异步模型写起来不友好。而fetch刚好替代了XMLHttpRequest 请求方法,但不是代替ajax技术,但fetch有个缺点就是兼容性不好,但刚好有个库,能够解决fetch的兼容性问题。https://github.com/camsong/fetch-ie8,这个库其实也就是将XMLHttpRequest封装起来的。接下来看看怎么来写
get方法
1、 fetch("/**.json").then(res=>res.json()).then(res=>{console.log(res)})
2、fetch("/**.json").then(res=>res.text()).then(res=>{console.log(res)})
res.json()为json格式;res.text()为文本格式
post方法:form编码格式
fetch("/**.json",{
method:"post",
headers:{
"Content‐Type": "application/x‐www‐form‐urlencoded"
},
body:"name=xiaoming&age=18" //请求体
}).then(res=>res.json()).then(res=>{
console.log(res)
})
post方法:json编码格式
fetch("/**.json",{
// credentials:"include",
method:"post",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify({
name:"xiaoming",
age:18
}) //请求体
}).then(res=>res.json()).then(res=>{
console.log(res)
})
注意:fetch 请求默认是不带 cookie 的,需要设置 credentials:‘include’
二、axios方法
axios相对于fetch是比较简单的。只需要引入axios这个库,就能使用
1.使用npm:
$ npm install axios
2.使用 bower:
$ bower install axios
3.使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
axios中get方法
axios.get("/**.json").then(res=>{
// res.data 才是真正的后端数据
console.log(res.data)
})
axios中post方法1
axios.post("json/test.json","name=xiaoming&age=18").then(res=>{
console.log(res.data)
})
axios中post方法2
axios.post("json/test.json",{
name:"xiaoming",
age:18
}).then(res=>{
console.log(res.data)
})
想要详细了解的,可以参考这个网址https://www.npmjs.com/package/axios。