1. 程式人生 > >jquery ajax防重複提交

jquery ajax防重複提交

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); } });