vue中发送ajax请求方法-fetch与axios

一、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。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值