# Ajax的使用 ###### tags: `Java Web-vue` #### HTML代碼 ```htmlembedded= <div id="div0"> uname:<input type="text" v-model="uname"/><br/> pwd:<input type="text" v-model="pwd"/><br/> <input type="button" @click="axios01" value="发送一个带普通请求参数值的异步请求"/> </div> ``` ### Axios語法 ```htmlembedded= axios({ //method分成post、get "method":"post", "url":"/demo/AjaxServlet?method=commonParam", //帶過去的參數 "params":{ //因為使用的vue值在axios外,因此不能用this,而使用變量名vue "userName":vue.uname", "userPwd":"vue.pwd" } //then:成功響應時進行回調 //value.data可以獲取到服務器響應內容 }).then(function (response) { console.log(response); //catch:有異常時執行的回調 //reason.response.data可以獲取到響應的內容 //reason.message/reason.stack 可以查看錯誤的信息 }).catch(function (error) { console.log(error); }); ``` #### Ajax代碼 ```htmlembedded= var vue = new Vue({ "el":"#div0", data:{ uname:"lina", pwd:"ok" }, methods:{ axios01:function(){ //axios:發出異步請求 axios({ method:"POST", url:"axios01.do", params:{ uname:vue.uname, pwd:vue.pwd } }) .then(function (value) { console.log(value); }) .catch(function (reason) { console.log(reason); }); } } }); ``` #### java代碼 ```java= @WebServlet("/axios01.do") public class Axios01Servlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String uname = request.getParameter("uname"); String pwd = request.getParameter("pwd"); System.out.println("uname = " + uname); System.out.println("pwd = " + pwd); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); //返回到客戶端,被axios的then接收,結果如下圖 out.write(uname+"_"+pwd); //請求失敗時會讓catch捕捉,拋出異常 throw new NullPointerException("这里故意抛出一个空指针异常...."); } } ``` ##### 客戶端響應給服務器端的內容 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up