Introduction to using the beforeSend method for jquery. Ajax

  • 2020-03-30 04:31:15
  • OfStack

A common effect is that when an ajax request is made, a small rotating loading icon or "content loading.." appears before the return. To tell the user that the data is being requested. This can be done using the beforeSend method.

Download demo: (link:

The code is as follows:

function test_ajax(){
      type:"GET",//There are usually two: GET and POST. The default is: GET
      url:"a.php",//(default: current page address) the address to which the request is sent is
      dataType:"html",//The type of data expected to be returned by the server. < br / >       beforeSend:beforeSend, //Send a request
      success:callback, //Request successful
      error:error,//Request error
      complete:complete//Request completed
function error(XMLHttpRequest, textStatus, errorThrown){
  //Usually only one of textStatus and errorThown has a value
  $("#showResult").append("<div> Request error! </div>");
function beforeSend(XMLHttpRequest){
  $("#showResult").append("<div><img src='loading.gif' /><div>");
function complete(XMLHttpRequest, textStatus){
function callback(msg){
  $("#showResult").append("<div> Request successful, return number :"+msg+"<div>");

Method beforeSend to add some handlers before sending a request to the server. This is an ajax event, before the start of the ajax request is triggered, usually allows the user to modify the XMLHttpRequest object (such as setting up additional header information), explanation of ajax incident may refer to documents: (link:

We've also seen a lot of sites that say "wait while the data is loaded," and then display the content when it's loaded. You can set the default text to appear as a hint in the load, and when the content is loaded, we can replace the text in the label with the final content through the ID selector. It's more efficient to replace beforeSend.

When using beforeSend, when replaced with text, and depends on the DOM elements before and after the ajax request you shown is consistent, if you have shown the DOM elements in the request before already exists, then through the textual substitution way to deal with will be better, if in addition to this you also need to increase the demand of the other, so still use beforeSend to handle it.

Related articles: