Axios异步通信

本文介绍了Axios作为异步通信工具的使用,包括Axios的定义、与Ajax的关系、使用Axios的原因以及详细的API和使用示例,如get和post请求的实现,通过实例展示了如何与服务器进行数据交互。

四.Axios异步通信

1 什么是Axios?

Axios是一个类库,基于Promise管理的HTTP 库,是前端通信框架,可以用在浏览器和 node.js 中。axios实现了对ajax的封装,常用于Ajax请求。

注解:promise是Java Script的一个对象,代表了未来将要发生的事件,用来传递异步操作的消息。

2 Axios和Ajax的关系

Axios是AJAX技术的一种实现,就像Jquery中的$.ajax也是AJAX技术的一种实现。

Axios是通过Promise实现XHR封装,其中Promise是控制手段,XHR是实际发送Http请求的客户端。

Jquery中的$.ajax是通过callback+XHR实现(XHR就是XmlHttpRequest对象)

再通俗一点讲:AJAX是汽车,Axios是奥迪,$.ajax是奔驰

3 为什么要用Axios?

因为vue的边界很明确,就是为了处理DOM,所以并不具备通信功能,为了解决通信问题,作者单独开发了一个名为 vue-resource 的插件,不过在进入 2.0 版本以后停止了对该插件的维护并推荐了 Axios 框架,此时就需要额外使用一个通信框架与服务器交互。

功能就像jQuery提供的AJAX通信功能。

4 Axios的API


axios({
	method: 'get',
	url: '/user/12345',
	data: {
	id:1,
	name:'aa'
	}
});

axios.get('url'[,'参数']).then(resp=>(this.user=resp.data));
        		
axios.post('url'[,'参数']).then(resp=>(this.user=resp.data));

axios.put('url'[,'参数']).then(resp=>(this.user=resp.data));

axios.delete('url'[,'参数']).then(resp=>(this.user=resp.data));

5 Axios的使用

​ axios提供了多种请求方式,比如直接发起get或post请求:

5.1.get请求

案例1

a.模拟后端接口传递回的json数据

咱们后端开发的接口大部分都是采用 JSON 格式,我们可以创建一个文件存放json数据用来模拟后端接口传递过来的数据。

user.json页面:模拟服务器端返回的数据

{
  "id":1,
  "name": "呆萌老师",
  "qq": "2398779723",
  "weixin":"it_daimeng",
  "address": {
    "country": "中国",
    "city": "上海"
   
  }
}

b.通过axios 跟服务器端 交互

​ index.html :

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script type="text/javascript" src="js/vue.js" ></script>
		<!--在线引入axios。在项目开发中会安装axios组件(npm install axios)-->
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
	</head>
	<body>
		
		<div id="app">
			
		  <input type="button" value="请求数据"  v-on:click="getUserInfo" />
			
		   <div>id:<span>{{user.id}}</span></div>
		   <div>name:<span>{{user.name}}</span></div>
		   <div>qq:<span>{{user.qq}}</span></div>
		   <div>weixin:<span>{{user.weixin}}</span></div>
		   <div>address:<span>{{user.address.country}}/{{user.address.city}}</span></div>
		
		</div>
		
		<script>
		
        var v=new Vue({
        	
        el:"#app",
       
        data:function(){//处理返回的数据   (后台返回的数据在页面上渲染时使用)
            return{
                //请求的返回参数格式必须和json字符串一样
                user:{
                	id:null,
                    name:null,//相当于形参占位,实际参数user.json会传递过来
                    qq:null,
                    weixin:null,
                    address:{
                        country:null,
                        city:null
                        
                    }
                }
            }
        },
        
        methods:{
        	
        	getUserInfo:function(){
        		
        		console.log("aaa");
        		
        	// axios.get('user.json').then(resp=>(console.log(resp.data)));
            // resp.data 存放的是响应回来的数据
            axios.get('user.json').then(resp=>(this.user=resp.data));
        		
        	}
        	
        }
        
//      //mounted钩子函数,页面加载时触发的函数
//      mounted:function(){
//         this.getUserInfo();
//      }
	    })
		</script>

		
		
		
	</body>
</html>


c.测试:

在这里插入图片描述

在这里插入图片描述

d.说明:

这里使用 axios 框架的 get 方法请求 AJAX 并自动将数据封装进了 Vue 实例的数据对象中
我们在data中的数据结构必须要和Ajax响应回来的数据格式匹配!

e.也可以设置参数:

// 为给定 ID 的 user 创建请求
axios.get('/user?id=1')
  .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);
  });

案例2:

带参数的get请求

a.准备服务器端代码,这里以java代码为例

package com.example.axios_test.controller;
import com.example.axios_test.pojo.User;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;

@RestController
public class UsersController {


      @GetMapping("/users/{id}")
      //设置跨域 允许客户端的域名访问此方法,注意看你自己的客户端域名
      @CrossOrigin(value = "http://127.0.0.1:8020")
      public User getUserById(@PathVariable("id") int id)
      {
                HashMap<Integer,User> hashMap=new HashMap<>();
                hashMap.put(1,new User(1,"汪老师"));
                hashMap.put(2,new User(2,"呆萌老师"));
                return hashMap.get(id);

      }
}

b.前端页面通过axios请求后端数据

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/vue.js" ></script>
		
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
	</head>
	<body>
		
	  	<div id="app">
			
		  <input type="button" value="请求数据"  v-on:click="getUserInfo(2)" />
			
		   <div>id:<span>{{user.id}}</span></div>
		   <div>name:<span>{{user.name}}</span></div>
		</div>
		
		<script>
		
        var v=new Vue({
        	
        el:"#app",
       
        data:function(){//处理返回的数据   (后台返回的数据在页面上渲染时使用)
            return{
                //请求的返回参数格式必须和json字符串一样
                user:{
                	id:null,
                    name:null
                }
            }
        },
        
        methods:{
        	
        	getUserInfo:function(id){
        
            axios.get('http://localhost:8080/users/'+id).then(resp=>(this.user=resp.data));
        		
        	}
        	
        }
        

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


c 测试

在这里插入图片描述

5.2.post请求
模拟一下用axios中用post方式提交表单数据,再处理返回结果

a.模拟服务器端接收前端提交的表单数据并处理

     @PostMapping("/users")
      @CrossOrigin(value = "http://127.0.0.1:8020")
      //如果发送请求过来的数据类型是json格式,则这里接收的时候 用 @RequestBody
      public String checkLogin(String uname,String upwd) {


          if(uname.equals("daimenglaoshi") && upwd.equals("666") )
          {

              return "ok";
          }
          else
          {
              return "error";
          }

      }

b.前端post方式提交表单数据

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/vue.js" ></script>
		<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
	</head>
	<body>
		
		
		<form action="method" id="loginForm" >
			
			用户名:<input type="text" name="uname" v-model="uname" />
			密码:<input type="password" name="upwd" v-model="upwd" />
			
			<input v-on:click="login" type="button" name="btn" value="登录" />
			
			
		</form>
		
		<script>
			
			var v=new Vue({
				
				el:"#loginForm",
				data:{				
					uname:"",
					upwd:""					
				},
				methods:{
					
					login:function(){						
					
						axios.post("http://localhost:8080/users","uname="+this.uname+"&upwd="+this.upwd).then(function(response) {
						    console.log(response);
						})
					
					}
					
					
				}
			})
			
			
		</script>
		
		
		
	</body>
</html>


c.测试

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值