The beforeSend method of jquery.ajax (solve the progress bar, "please wait" prompt, etc...)

A common effect is that when an ajax request is used, a small rotating loading icon or "content loading.." will appear before returning to inform the user that data is being requested. This can be achieved with the beforeSend method.

Download demo: ajax loading

code show as below:

copy code code show as below:

function test_ajax(){
   $.ajax(
   {
      type:"GET",//Two types are usually used: GET, POST. The default is: GET
      url:"a.php",//(Default: current page address) The address to send the request
      dataType:"html",//The expected data type returned by the
      server.beforeSend:beforeSend, //Send the request
      success:callback, //The request is successful
      error:error,//The request is wrong 
      complete:complete//The request is completed
   });
}
function error(XMLHttpRequest, textStatus, errorThrown){
  // Usually only one of textStatus and errorThown has a value 
  $("#showResult").append("<div>The request went wrong!</div>" );
}
function beforeSend(XMLHttpRequest){
  $("#showResult").append("<div><img src='loading. gif' /><div>");
}
function complete(XMLHttpRequest, textStatus){
  $("#showResult").remove();
}
function callback(msg){
  $("#showResult").append("<div>请求成功,回传数:"+msg+"<div>");
}

The method beforeSend is used to add some handler functions before sending the request to the server. This is an ajax event that is fired before an ajax request starts. It usually allows the user to modify the XMLHttpRequest object (for example, to set additional header information). For an explanation of the ajax event, please refer to the documentation: http://docs.jquery.com /Ajax_Events

We have also seen a situation where many websites give a "data loading, please wait" prompt during the process of loading content, and display the content when the content is loaded. You can set the default text to be displayed as the loading prompt. When the content is loaded, we can use the ID selector to replace the text in the label with the final content. It is more efficient to replace beforeSend with this.

When to use beforeSend and when to replace with text depends on whether the DOM elements you display before and after the ajax request are consistent. If the DOM elements you display already exist before the request, it will be better to deal with the above text replacement method. If you need to add other requirements in addition to this, then use beforeSend to handle it.

Guess you like

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