在 Vue 中发送异步请求,本质上还是 AJAX。我们可以使用 axios 这个插件来简化操作。
使用步骤
引入axios与vue核心js文件。调用axios对象的方法来发起异步请求。调用axios对象的方法来处理服务器响应数据。axios常用方法
方法名作用get(请求的资源路径与请求的参数)发起GET方式请求post(请求的资源路径,请求的参数)发起POST方式请求then(response)请求成功后的回调函数,通过回调参数response获取响应的数据catch(error)请求失败后的回调函数,通过毁掉参数error获取错误信息代码示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>异步操作</title> <script src="js/vue.js"></script> <script src="js/axios-0.18.0.js"></script> </head> <body> <div id="div"> {{name}} <!--为按钮绑定单击事件--> <button @click="send()">发起请求</button> </div> </body> <script> /** * 创建vue对象 */ new Vue({ //指定此vue对象解析的模板区域 el: "#div", //定义属性 data: { name: "张三" }, //定义函数 methods: { send: function () { /* 使用axios对象的get()方法发起异步请求 get()方法参数就是要请求的服务器地址,要提交的参数在请求地址处进行拼接 this:vue对象中的this代表的都是其所在的vue对象 */ //then()方法为请求成功所执行的方法。 axios.get("testServlet?name=" + this.name).then(response => { //response:是then()的回调参数,通过response.data就能拿到服务响应的数据 console.log(response.data); //error()方法为请求失败所执行的方法 }).catch(error => { console.log(error); }); } } }); </script> </html>代码示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>异步操作</title> <script src="js/vue.js"></script> <script src="js/axios-0.18.0.js"></script> </head> <body> <div id="div"> {{name}} <!--为按钮绑定单击事件--> <button @click="send()">发起请求</button> </div> </body> <script> /** * 创建vue对象 */ new Vue({ //指定此vue对象解析的模板区域 el: "#div", //定义属性 data: { name: "张三" }, //定义函数 methods: { send: function () { /* 使用axios对象的get()方法发起异步请求 post()方法参数1就是要请求的服务器地址, 参数2:就是要提交的参数, 多个参数进行拼接。 this:vue对象中的this代表的都是其所在的vue对象 */ //then()方法为请求成功所执行的方法。 axios.post("testServlet", "name=" + this.name).then(response => { //response:是then()的回调参数,通过response.data就能拿到服务响应的数据 console.log(response.data); //error()方法为请求失败所执行的方法 }).catch(error => { console.log(error); }); } } }); </script> </html>未完…