PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

博客列表 > vue实战使用ajax请求后台数据

vue实战使用ajax请求后台数据

阿杰
阿杰 原创
2020年07月15日 10:39:18 2406浏览

Axios的安装和引入

  1. 使用npm安装:
    1. $npm install axios -S
  2. 在vue项目公共文件(我这里是main.js文件)中引入:
    1. import axios from "axios";
  3. axios跟很多第三方模块不同的一点是它不能直接使用use方法,而是用下面这种方法:
    1. Vue.prototype.$axios = axios;
  4. 这样呢在methods里用到的时候直接用this.$axios来调用它:
    1. this.$axios.get(接口地址).then(function(respon){}).catch(function(error){})

axios.get

  1. 通过params选项来传递参数的格式是 axios.get(‘url’,{params:{key:value}}).then() ;

    1. this.$axios.get("http://api.xdclass.net:8081/pub/api/v1/web/list_buyer",{
    2. params:{
    3. video_id:4
    4. }
    5. }).then(res=>{
    6. console.log(res);
    7. }).catch(function(error){
    8. })

axios.post

  1. 通过params选项来传递参数的格式是 axios.get(‘url’,{params:{key:value}}).then() ;

    1. this.$axios.post("https://nmapi.rdxsaj.com/v1/Indexc",{
    2. params:{
    3. token:'050e26b301245052c8ef807677025bb2',
    4. com_id:19792
    5. }
    6. }).then(res=>{
    7. console.log(res);
    8. }).catch(function(error){
    9. })

    会出现跨域问题,因为axios本身并不支持发送跨域的请求

    解决方案:通过字符串的方式发送数据

    1. this.$axios.post("https://nmapi.rdxsaj.com/v1/Indexc",'token=050e26b301245052c8ef807677025bb2&com_id=19792').then(res=>{
    2. console.log(res.data.data);
    3. }).catch(function(error){
    4. })

用qs来解决post跨域问题

  1. 安装qs:
    1. npm install --save axios vue-axios qs
    2. import qs from 'qs' qs 用来解决vue中post请求以 a=a&b=b 的格式
  2. main.js 内容:
    1. import axios from "axios"
    2. import qs from "qs"
    3. Vue.prototype.$axios = axios
    4. Vue.prototype.$qs = qs
  3. 需要的页面请求接口时 get 和post 两种方法:

    1. getbuyer:function(){
    2. this.$axios.get("http://api.xdclass.net:8081/pub/api/v1/web/list_buyer",{
    3. params:{
    4. video_id:4
    5. }
    6. }).then(res=>{
    7. console.log(res);
    8. }).catch(function(error){
    9. })
    10. },
    11. getData:function(){
    12. this.$axios.post("https://nmapi.rdxsaj.com/v1/Indexc",
    13. this.$qs.stringify({
    14. token:'050e26b301245052c8ef807677025bb2',
    15. com_id:19792
    16. })
    17. ).then(res=>{
    18. console.log(res);
    19. }).catch(function(error){
    20. })
    21. }

    请求成功

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议