The usefulness of beforeSend of Ajax

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:

// Submit form data to background processing
$.ajax({
    type: "post",
    data: studentInfo,
    contentType: "application/json",
    url: "/Home/Submit",
    beforeSend: function () {
        // disable button to prevent duplicate submission
        $("#submit").attr({ disabled: "disabled" });
    },
    success: function (data) {
        if (data == "Success") {
            //Clear the input box
            clearBox ();
        }
    },
    complete: function () {
        $("#submit").removeAttr("disabled");
    },
    error: function (data) {
        console.info("error: " + data.responseText);
    }
});

Simulate toast effect

When ajax requests the server to load the data list, it prompts loading("Loading, please wait..."),

$.ajax({
	beforeSend : function(){
		showWaiting();
		$("#loadInfo").empty().append("Getting file contents...");  
	},


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326720856&siteId=291194637