axios

vue.js没有集成ajax功能,要使用ajax功能,可以使用vue官方推荐的axios.js库来做ajax的交互。

只列出常用的,详细可见:https://www.kancloud.cn/yunye/axios/234845

  • 执行GET请求

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 可选地,上面的请求可以这样做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

 

  • 执行POST请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

 

  • 执行成功返回的Response对象(部分属性)

{ 
  status: 200,
  data: {
     user_id: 10,
     username: 'python'
  },
  headers: {}
}

// 取值
response.status
response.data.user_id
response.data.username

 

  • 执行失败返回的error对象(部分属性)

{
    message : "Request failed with status code 500",
    response : {
        status : 500,
        data : {
            // 错误详情的信息,一个错误的话就只有一条            
            "mobile": ["该字段不能为空。"],
            "allow": ["请同意协议"],
            "sms_codes": ["该字段不能为空。"],
            "password2": ["该字段不能为空。"],
            "username": ["该字段不能为空。"],
            "password": ["该字段不能为空。"]
        }
        headers : {}
    }
}

// 取值
error.response.data.detail
error.response.data.username[0]
error.response.data.non_field_errors[0]

 

posted @ 2018-11-12 21:13  苦瓜爆炒牛肉  阅读(173)  评论(0编辑  收藏  举报