Home > Web Front-end > JS Tutorial > Clever use of Ajax's beforeSend method in Jquery_jquery

Clever use of Ajax's beforeSend method in Jquery_jquery

WBOY
Release: 2016-05-16 15:18:57
Original
1389 people have browsed it

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.

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

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 thinks that the operation is not successful, and then repeats the submit button operation times. If the front-end code of the page does not do some corresponding processing, it usually leads to multiple The same data is inserted into the database, resulting in an increase in dirty data. To avoid this phenomenon, disable the submit button in the beforeSend method of the $.ajax request, wait until the Ajax request is completed, and then restore the button's available state.

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);
  }
});
Copy after login

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

$.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);
  }
});
Copy after login

The method beforeSend is used to add some processing functions before sending a request to the server. I hope this article will deepen everyone's understanding of the beforeSend method.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template