温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue中如何发送ajax请求

发布时间:2021-06-15 16:29:34 来源:亿速云 阅读:524 作者:Leah 栏目:web开发

这期内容当中小编将会给大家带来有关vue中如何发送ajax请求,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

首页安装并引入axios

1、npm install axios -S        #直接下载axios组件,下载完毕后axios.js就存放在node_modules\axios\dist中

2、网上直接下载axios.min.js文件

3、通过script src的方式进行文件的引入<script src="js/axios.min.js"></script>

axios基本使用方法

发送get请求

1、基本使用格式

格式1:axios([options]) #这种格式直接将所有数据写在options里,options其实是个字典

格式2:axios.get(url[,options]);

2、传参方式:

通过url传参

通过params选项传参

下面我们来看一个vue发送ajax get请求实例代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>发送AJAX请求</title>
  <script src="js/vue.js"></script>
  <script src="js/axios.min.js"></script>
  <script>
    window.onload=function(){
      new Vue({
        el:'#itany',
        data:{
          user:{
            name:'alice',
            age:19
          },
        },
        methods:{
          send(){
            axios({
              method:'get',
              url:'http://www.baidu.com?name=tom&age=23'
            }).then(function(resp){
              console.log(resp.data);
            }).catch(resp => {
              console.log('请求失败:'+resp.status+','+resp.statusText);
            });
          },
          sendGet(){
            axios.get('server.php',{
              params:{
                name:'alice',
                age:19
              }
            })
            .then(resp => {
              console.log(resp.data);
            }).catch(err => {       //
              console.log('请求失败:'+err.status+','+err.statusText);
            });
          },
        }
      });
    }
  </script>
</head>
<body>
  <div id="itany">
    <button @click="send">发送AJAX请求</button>

    <button @click="sendGet">GET方式发送AJAX请求</button>

  </div>
</body>
</html>

发送post请求(push,delete的非get方式的请求都一样)

1、基本使用格式

格式:axios.post(url,data,[options]);

2、传参方式

1、自己拼接为键值对

2、使用transformRequest,在请求发送前将请求数据进行转换

3、如果使用模块化开发,可以使用qs模块进行转换

4、注释:axios默认发送post数据时,数据格式是Request Payload,并非我们常用的Form Data格式,所以参数必须要以键值对形式传递,不能以json形式传参

下面看是一个vue发送ajax post请求实例代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>发送AJAX请求</title>
  <script src="js/vue.js"></script>
  <script src="js/axios.min.js"></script>
  <script>
    window.onload=function(){
      new Vue({
        el:'#itany',
        data:{
          user:{
            name:'alice',
            age:19
          },
        },
        methods:{
          sendPost(){
            // axios.post('server.php',{
            //     name:'alice',
            //     age:19
            // }) //该方式发送数据是一个Request Payload的数据格式,一般的数据格式是Form Data格式,所有发送不出去数据
            // axios.post('server.php','name=alice&age=20&') //方式1通过字符串的方式发送数据
            axios.post('server.php',this.user,{ //方式2通过transformRequest方法发送数据,本质还是将数据拼接成字符串
              transformRequest:[
                function(data){
                  let params='';
                  for(let index in data){
                    params+=index+'='+data[index]+'&';
                  }
                  return params;
                }
              ]
            })
            .then(resp => {
              console.log(resp.data);
            }).catch(err => {
              console.log('请求失败:'+err.status+','+err.statusText);
            });
          },
        }
      });
    }
  </script>
</head>
<body>
  <div id="itany">
    <button @click="send">发送AJAX请求</button>

    <button @click="sendGet">GET方式发送AJAX请求</button>

  </div>
</body>
</html>

上面我们所介绍的vue发送ajax请求都是在同一域名下进行的也就是同域或者说是同源

那么vue如何发送跨域的ajax请求呢?

vue发送跨域ajax请求

1、须知:axios本身并不支持发送跨域的请求,没有提供相应的API,作者也暂没计划在axios添加支持发送跨域请求,所以只能使用第三方库

2、使用vue-resource发送跨域请求

3、 安装vue-resource并引入   

npm info vue-resource           #查看vue-resource 版本信息

cnpm install vue-resource -S #等同于cnpm install vue-resource -save

4、基本使用方法(使用this.$http发送请求)

this.$http.get(url, [options])

this.$http.head(url, [options])

this.$http.delete(url, [options])

this.$http.jsonp(url, [options])

this.$http.post(url, [body], [options])

this.$http.put(url, [body], [options])

this.$http.patch(url, [body], [options])

下面再来看两个实例

向360搜索发送数据

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>发送AJAX请求</title>
  <script src="js/vue.js"></script>
  <script src="js/axios.js"></script>
  <script src="js/vue-resource.js"></script>
</head>

<body>
<div id="itany">
  <a>{{name}}</a>

  <button v-on:click="send">sendJSONP</button>

</div>
</body>
<script>
  new Vue({
    el: '#itany',
    data:{
      name: 'alice',
      age: 19
          },
    methods:{
      send:function(){
//        https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word=a
        this.$http.jsonp('https://sug.so.360.cn/suggest',
          {params:{
            word:'a'
          }}
        ).then(function (resp) {
          console.log(resp.data)
        })

      }
    }
  })
</script>
</html>

vue发送跨域ajax请求带jsonp参数

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>发送AJAX请求</title>
  <script src="js/vue.js"></script>
  <script src="js/axios.js"></script>
  <script src="js/vue-resource.js"></script>
</head>
<body>
<div id="itany">
  <button v-on:click="send">向百度搜索发送JSONP请求</button>
</div>
</body>
<script>
  new Vue({
    el:'#itany',
    data:{
      name:'za'
    },
    methods:{
      send:function () {
        this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',
          {params:{wd:'a'},
            jsonp:'cb', //百度使用的jsonp参数名为cb,所以需要修改,默认使用的是callbakc参数就不用修改
          }).then(function (resp) {
          console.log(resp.data)
        }).catch(function (err) {
          console.log(err)
        })
      }
    }


  })
</script>
</html>

Vue作为一个没有入侵性的框架并不限制你使用ajax框架

使用了Vue后,ajax部分你可以做如下选择:

1.使用JS原生XHR接口

2.引入JQuery或者Zepto 使用$.ajax();

3.Vue的github上提供了vue-resource插件 :

4.使用 fetch.js

5.自己封装一个ajax库

上述就是小编为大家分享的vue中如何发送ajax请求了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI