Detailed explanation of ajax. load of method in jQuery

  • 2021-07-15 03:36:12
  • OfStack

jQuery load () method

The jQuery load () method is a simple but powerful AJAX method.

The load () method loads data from the server and places the returned data into the selected element.

Syntax:


$(selector).load(URL,data,callback);

The load () function loads data from the server and replaces the contents of the current matching element with the returned html contents.

The load () function defaults to GET and automatically switches to POST if data in object form is provided.

Because Get request mode is used by default, we can also submit data in url.

For example $("#box").load("loadTest.html?name=zhang&age=25")

The load () method can take three arguments:

url (required, request the url address of the html file, parameter type String)

data (optional, key/value data sent, parameter type Object)

callback (optional, successful or failed callback function with argument type function Function)

The load () method is local because it requires an jQuery object containing the element as a prefix. For example $("# box"). load ()

While $. get () and $. post () are global methods and do not need to specify an element. For purposes,. load () is suitable for asynchronous retrieval of static files,

For those who need to pass parameters to the server page, $. get () and $. post () are more appropriate.

The optional callback parameter specifies the callback function to be allowed when the load () method completes. Callback functions can set different parameters:

responseTxt-Contains the result content when the call is successful statusTXT-Contains the state of the call xhr-Contains XMLHttpRequest objects

The following example displays a prompt box after the load () method completes. If the load () method has succeeded, it displays "external content loaded successfully!" And if it fails, an error message is displayed:


 $("button").click(function(){
 $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
  if(statusTxt=="success")
   alert(" External content loaded successfully! ");
  if(statusTxt=="error")
   alert("Error: "+xhr.status+": "+xhr.statusText);
 });
});

Related articles: