jquery ajax防重複提交

巧用Ajax的beforeSend 提高用戶體驗

jQuery是經常使用的一個開源js框架,其中的$.ajax請求中有一個beforeSend方法,用於在向服務器發送請求前執行一些動作。
具體可參考jQuery官方文檔:http://api.jquery.com/Ajax_Events/

$.ajax({
    beforeSend: function(){
     // Handle the beforeSend event
    },
    complete: function(){
     // Handle the complete event
    }
    // ......
});

防止重複數據

在實際項目開發中,提交表單時常常由於網絡或者其原因,用戶點擊提交按鈕誤認爲自己沒有操作成功,進而會重複提交按鈕操作次數,如果頁面前端代碼沒有做一些相應的處理,通常會導致多條同樣的數據插入數據庫,導致髒數據的增加。要避免這種現象,在$.ajax請求中的beforeSend方法中把提交按鈕禁用掉,等到Ajax請求執行完畢,在恢復按鈕的可用狀態。

舉個例子:

// 提交表單數據到後臺處理
$.ajax({
    type: "post",
    data: studentInfo,
    contentType: "application/json",
    url: "/Home/Submit",
    beforeSend: function () {
        // 禁用按鈕防止重複提交
        $("#submit").attr({ disabled: "disabled" });
    },
    success: function (data) {
        if (data == "Success") {
            //清空輸入框
            clearBox();
        }
    },
    complete: function () {
        $("#submit").removeAttr("disabled");
    },
    error: function (data) {
        console.info("error: " + data.responseText);
    }
});

模擬Toast效果

ajax請求服務器加載數據列表時提示loading(“加載中,請稍後...”),

$.ajax({
    type: "post",
    contentType: "application/json",
    url: "/Home/GetList",
    beforeSend: function () {
        $("loading").show();
    },
    success: function (data) {
        if (data == "Success") {
            // ...
        }
    },
    complete: function () {
        $("loading").hide();
    },
    error: function (data) {
        console.info("error: " + data.responseText);
    }
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章