vue中两种数据请求方式

axios:

  1. axios属于第三方插件,需要引入。
  2. axios返回的结果是一个Promise对象。
  3. get方式的请求:
第一种写法
axios.get('http://localhost:8080/xxx.php', {
method : 'get',
  params : {
    a : 1,
    b : 2
  }
}).then ( (res) =>{
 console.log(res); 
}).catch(err = > {
  if(err){
  console.log(err)
  }
})
第二种写法:
axios({
 url : 'http://localhost:8080/xxx.php'',
 method : 'get',
 params : {
  a : 1,
  b : 2
 }
}).then ( ( res ) => {
   console.log(res);
}).catch(err => {
    if(err){
      console.log(err)
     })
})
  1. post请求:
在写post请求前需要做如下几步准备:
1.统一设置请求头:
 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
 2.使用URLSearchParams实例化一个promise对象
 3.使用promise对象的append方法添加数据
 代码如下:
 
 
   axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
   let params = new URLSearchParams()
   params.append('a',1)
   params.append('b',2)
   
   new Vue({
        el: '#app',
        methods: {
          axiosGetHandler(){
          axios({
          url : 'http://localhost:8080/xxx.php'',
          method : 'post',
          data : params,
          headers : {
          'Content-Type': "application/x-www-form-urlencoded"
          }
          }).then(res => {
            console.log(res)
          }).catch(err =>{
             if(err){
             console.log(err);
             }
          })

fetchf方法:

1.get:

new Vue({
     el : '.app',
     data : {
        numobj : {
           a : 1,
           b : 2
        }
     },
     methods : {
       get(){
       //输出结果也是promise对象
       fetch('http://localhost/get.php?a=1&b=2')
       .then(res =>{
          res.text();
       })
       .then(data => {
         console.log(data);
       })
       .catch(err =>{
         console.log(err)
       })
       }
     }

})

如果不要传送数据的话:

fetch('data.json')
.then(res => {
   res.json() //res.text() res.blob()
})
.then( data => console.log(data) )
.catch (err => console.log(err))

post方式:

post方式和axios一样都需要设置请求头,实例化URLSearchParams,且在fetch的中,post里的数据存储在body中,写法如下:

post(){
  fetch('http://localhost/post.php',{
        method : 'post',
        //设置请求头:
        headers : new Header({
          'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交
        }),
        body : new URLSearchParams([["a", 1],["b", 2]]).toString()
  })
  .then( res => res.text())
  .then( data => console.log(data))
  .catch( err => {
      if(err){
        console.log(err)
      }
  })
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值