Ajax beforeSend and complete to improve the user experience of Ajax requests

Use Ajax's beforeSend skillfully to improve user experience

jQuery is an open source js framework that is often used. There is a beforeSend method in the $.ajax request, which is used to perform some actions before sending the request to the server.
For details, please refer to the official jQuery documentation: http://api.jquery.com/Ajax_Events/

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

prevent duplicate data

In actual project development, when submitting a form, often due to the network or other reasons, the user clicks the submit button and mistakenly believes that he did not operate successfully, and then repeats the submit button operation times. The same data is inserted into the database, resulting in the increase of dirty data. To avoid this phenomenon, disable the submit button in the beforeSend method of the $.ajax request, wait until the Ajax request is executed, and restore the available state of the button.

for example:

// 提交表单数据到后台处理
$.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);
    }
});

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325390258&siteId=291194637