Ajax beforeSend和complete 方法与防止重复提交

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

其中的$.ajax请求中有一个beforeSend方法,用于在向服务器发送请求前执行一些动作。

complete 方法执行完后调用

用途

防止重复数据

// 提交表单数据到后台处理
$.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({
    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);
    }
});
原文地址:https://www.cnblogs.com/axu92312/p/6101567.html