內容目錄
jQuery 與 Axios 對於 spring boot 的 ajax 請求處理
ajax 請求處理
現行的網頁操作使用 ajax 技術來節省頻寛,加快伺服器的回應時間,讓使用者取得良好的操作體驗已是趨勢。之前的文章已具備基本的運作系統架構,接下來開始要處理網頁與伺服器間的資料傳遞,經伺服器處理後回傳到前端網頁。說到 ajax 就會直覺想到 jQuery,但若想與 Vue.js 結合,則不妨使用Axios。
Javascript 的前端
下面是一小段的 Javascript ,分別用 jQuery 與 Axios 來向伺服器提出 post 的請求。
var data = {email: App.resetPasswordForm.email}; $.post('/user/password/reset', data, function (response) { App.fullscreenLoading = false; alert('Send success!!' ); }) .error(function(response) { App.fullscreenLoading = false; alert("Oops! Sorry error occurred! Internet issue."); }); axios.post('/rest/user/password/reset', data) .then(function (response) { console.log(response); }) .catch(error=> { console.log(error); }) .finally(() => { App.fullscreenLoading = false; })
若對於伺服器回覆的訊息要進一步處理,可以參考下方的 Javascript ,要注意的是:要取得伺服器回傳的 Json 值,要先加入 response.
data
。
axios.post('/user/password/reset', data) .then(function (response) { App.responseMessage = response.data.email; }) .catch(error=> { if (error.response.status === 400){ App.responseMessage=error.response.data.error.message; } console.log(error); }) .finally(() => { App.fullscreenLoading = false; })
jQuery post 的分析
從下圖可以得知, jQuery post 預設是傳了一個 Request Param: email
, value: [email protected]
。
伺服器端的承接方式,要用 @RequestParam("email") String email
。
@RequestMapping("/rest/user/password/reset") @ResponseBody public ResponseEntity<?> resetUserPassword(HttpServletRequest request, @RequestParam("email") String email) { Map<String,Object> responseJson = new HashMap<String,Object>(); Map<String,Object> responseError = new HashMap<String,Object>(); String token = UUID.randomUUID().toString(); return ResponseEntity .ok() .contentType(MediaType.APPLICATION_JSON) .body(responseJson); }
Axios post 的分析
從下圖可以得知, Axios post 預設是傳了一個 json 值:{"email":"[email protected]"}
。
伺服器端的承接方式,要用 @RequestBody Map<String,String> params)
。
@RequestMapping("/user/password/reset") @ResponseBody public ResponseEntity<?> resetPassword(HttpServletRequest request, @RequestBody Map<String,String> params) { Map<String,Object> responseJson = new HashMap<String,Object>(); Map<String,Object> responseError = new HashMap<String,Object>(); String token = UUID.randomUUID().toString(); return ResponseEntity .ok() .contentType(MediaType.APPLICATION_JSON) .body(responseJson); }
最後要注意一點的是,因為這是向伺服器提出請求,所以要在 WebSecurity
設定允許的通道,不是 HttpSecurity
,如:第4行,當然,若不想逐一設定請求網址,也可以用 HttpMethod.POST 或 HttpMethod.GET,如第5行,只是這樣方便了,但安全性降低了。
@Override public void configure(WebSecurity web) throws Exception { //allow ajax requests web.ignoring().antMatchers("/user/password/reset"); web.ignoring().antMatchers(HttpMethod.POST,HttpMethod.GET); }
Axios post 請求表示式的分析
直接送出請求:
一進入程式就馬上執行
# 注意: apiRefreshToken 這時候, 並不是一個函式 export const apiRefreshToken = axios.post("/jwt/refresh-token").then(res=>res.data);
函數的方式送出請求:
要呼叫此函數才會執行
# 函式的撰寫方式如下, 這是表式沒有參數要送出 export const apiRefreshToken = () => axios.post("/jwt/refresh-token").then(res=>res.data);
定義成 class 方式
先定義一個 class
import axios from '../plugins/axios.js'; # 將所有的請求, 綁定在一個 class 裡 export default class sysService { # 一般寫法 getWhoisin() { return axios.post("/user/whoisin").then(res=>res.data); } # 也可以寫成這樣, 比較精簡 getUserList = () => axios.post("/user/list").then(res=>res.data.users); #若傳送的參數只有一個, 可以省略括弧: 由 (data) 變成只寫 data toggleUserEnable = data => axios.post('/user/toggleEnable', data).then(res=>res.data); }
在 Vue.js 中使用
<script> import sysService from '../services/sysService.js' export default { data(){ return { whoisin: null, sysService: null, } }, created() { this.sysService = new sysService(); }, mounted() { this.sysService.getWhoisin().then(data => this.whoisin = data); }, methods: { refreshWhoisin() { this.sysService.getWhoisin().then(data => this.whoisin = data); } } } </script>
你必須 登入 才能發表評論。