简单了解Vue的异步请求,axios-0.18.0.js插件实现异步
生活随笔
收集整理的這篇文章主要介紹了
简单了解Vue的异步请求,axios-0.18.0.js插件实现异步
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Vue的異步請求
Vue 異步操作
在 Vue 中發送異步請求,本質上還是 AJAX。我們可以使用 axios 這個插件來簡化操作!
使用步驟
案列結構
前端代碼(test.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>new Vue({el:"#div",data:{name:"張三"},methods:{//上面綁定了點擊事件,執行異步請求send(){// GET方式請求// axios.get("testServlet?name=" + this.name)// .then(resp => {// alert(resp.data);// })// .catch(error => {// alert(error);// })/*? 在 Vue 中發送異步請求,本質上還是 AJAX。我們可以使用 axios 這個插件來簡化操作!? 使用步驟1. 引入 axios 核心 js 文件。2. 調用 axios 對象的方法來發起異步請求。3. 調用 axios 對象的方法來處理響應的數據。*/// POST方式請求,鏈式編程axios.post("testServlet","name="+this.name)//請求后回調函數發起請求后,然后呢//請求成功后的回調函數,通過response獲取響應的數據/*箭頭函數:特點:它能夠使用上下文的this*/.then(resp => {alert(resp.data);})//請求失敗后的回調函數,通過error獲取錯誤信息.catch(error => {alert(error);})//第二種模擬詳細流程使用的餓了么ui//說明表單校驗通過,發生異步請求//對響應的結果,axios對后端返回的結果進行了封裝,res.data,這個data就是返回的json數據,,,也可以從res中獲取響應碼等數據axios.post("/checkItem/edit.do",this.formData).then((res)=>{//提交后關閉編輯窗口this.dialogFormVisible4Edit=false;//對返回的數據進行判斷是否成功if(res.data.flag){//說明成功this.$message({message:res.data.message,type:"success"})}else {//說明失敗this.$message.error(res.data.message);return false;}}).finally(()=>{//finally()方法,表示異步提交后,無論成功還是失敗,都會執行的方法//無論成功還是失敗,都調用表單查詢方法this.findPage();}).catch((res)=>{//異步請求失敗,會走到catch這個方法this.$message.error("異步請求失敗~~~");}) //鏈式編程// axios.get("testServlet?name="+this.name).then(resp =>{alert(resp.data)}).catch(error=>{alert(error)});}}}); </script> </html>后端代碼(Servlet)
package com.fs;import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/testServlet") public class TestServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//設置請求和響應的編碼req.setCharacterEncoding("UTF-8");resp.setContentType("text/html;charset=UTF-8");//獲取請求參數String name = req.getParameter("name");System.out.println(name);//響應客戶端resp.getWriter().write("請求成功");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doGet(req,resp);} }圖解異步代碼
總結
以上是生活随笔為你收集整理的简单了解Vue的异步请求,axios-0.18.0.js插件实现异步的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 简单了解Vue的自定义组件与生命周期
- 下一篇: 前端学习笔记之-VUE框架学习-Vue核