Home  >  Article  >  Web Front-end  >  Introduction to the use of the beforeSend method of jquery.ajax_jquery

Introduction to the use of the beforeSend method of jquery.ajax_jquery

WBOY
WBOYOriginal
2016-05-16 16:28:291688browse

A common effect is that when making an ajax request, 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 using the beforeSend method.

Download demo: ajax loading

The code is as follows:

Copy code The code is as follows:

function test_ajax(){
$.ajax(
{
Type: "GET", // Usually two types are used: GET and POST. The default is: GET
URL: "a.php", // (Default: current page address) The address to send the request
DataType: "html", //The data type expected to be returned by the server.
​​ beforeSend:beforeSend, //Send 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("
Request error!
");
}
function beforeSend(XMLHttpRequest){
$("#showResult").append("
");
}
function complete(XMLHttpRequest, textStatus){
$("#showResult").remove();
}
function callback(msg){
$("#showResult").append("
Request successful, number returned:" msg "
");
}

The method beforeSend is used to add some processing functions before sending the request to the server. This is an ajax event, which is triggered before the ajax request starts. It usually allows users to modify the XMLHttpRequest object (such as setting 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 prompt of "data loading, please wait" during the process of loading content, and display the content after the content is loaded. You can set the default text to be displayed as a loading prompt. When the content is loaded, we can replace the text in the tag with the final content through the ID selector. Use this to replace beforeSend, which is more efficient.

When to use beforeSend and when to use text replacement 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, then use the above text replacement method to handle it. It will be better. If you need to add other requirements in addition, then use beforeSend to handle it.

Statement:
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