Axios异步通信

四.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的APIaxios({ 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”: “呆萌老师”, “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;@RestControllerpublic 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.测试

正如我总是意犹未尽的想起你。

Axios异步通信

相关文章:

你感兴趣的文章:

标签云: