1. 程式人生 > >使用Ajax提交資料,進行前後臺數據互動

使用Ajax提交資料,進行前後臺數據互動

HTML程式碼:

<input class="form-control" id="username" name="username" type="text"/>
<input class="form-control" id="password" name="password" type="password"/>

<button type="button" onclick="loginSubmit()">立即登入</button>

jQuery程式碼:

function loginSubmit() {

        var username = $("#username"
).val(); // 獲取id為username的<input>框資料 var password = $("#password").val(); // 獲取id為password的<input>框資料 // 判斷 if (username.length == 0) { $("#username").tips({msg: "請輸入使用者名稱。"}); return; } if (password.length == 0) { $("#password"
).tips({msg: "請輸入密碼。"}); return; } // Ajax提交資料 $.ajax({ url: "admin/check_login", // 提交到controller的url路徑 type: "post", // 提交方式 data: {"username": username, "password": password}, // data為String型別,必須為 Key/Value 格式。 dataType: "json"
, // 伺服器端返回的資料型別 success: function (data) { // 請求成功後的回撥函式,其中的引數data為controller返回的map,也就是說,@ResponseBody將返回的map轉化為JSON格式的資料,然後通過data這個引數取JSON資料中的值 if (data.message == "success") { //跳轉到系統首頁 ...... } else { ...... } }, }); }

Ajax中success回撥函式:
success: function(data)是Ajax在請求成功後自動呼叫的,所以這個方法是Ajax呼叫的,那麼該方法的引數(data)便是Ajax提供的了。其中function(data)的引數data是客戶端請求後臺,由後臺返回的值。

Controller程式碼:

    @RequestMapping(value = "check_login",method = RequestMethod.POST)
    @ResponseBody
    public Map checkLogin(
            @RequestParam(value = "username") String username,
            @RequestParam(value = "password") String password){
        Map<String,Object> map = new HashMap<>();
        // 呼叫service查詢資料庫驗證登入資訊
        ......
        // 判斷使用者是否存在
        if (user != null){
                map.put("message", "success");
                return map;
        } else {
            ......
        }
    }

ajax會根據其中的url來找到對應的controller方法,@RequestParam會得到Ajax傳過來的資料(即:data: {“username”: username, “password”: password}),並將其自動傳入到方法形參中。service就可以使用形參值來獲取資料了。controller方法呼叫完成後,Ajax會執行success回撥函式,判斷controller返回的map中的值是否為success。
使用Ajax提交代替傳統的form表單提交的好處在於,Ajax使用非同步方式與伺服器通訊,不需要打斷使用者的操作,具有更加迅速的響應能力。