An load of method usage instance of ajax in jQuery

  • 2020-05-10 17:37:04
  • OfStack

This article illustrates the use of the load() method for ajax in jQuery as an example. Share with you for your reference. The specific analysis is as follows:

The simple and powerful ajax method in this function jQuery.
It can load the content from the server and then write the matching element.
Grammatical structure:

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

Parameter analysis:

1.selector: a selector that loads content into the element that this selector matches.
2.URL: must, need to load 1 url address.
3.data: optional collection of key/value pairs of query strings sent with request 1.
4.callback: optionally, the function to be executed after the load() function is completed is a callback function.

Code example:


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="//www.ofstack.com/" />
<title> The home of the script </title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#bt").click(function(){
    $("#thediv").load("mytest/demo/antzone.txt");
  })
})
</script>
</head>
<body>
<div id="thediv"></div>
<input type="button" value=" See the effect " id="bt"/>
</body>
</html>

The above code implements our requirement to write the contents of the text file to the div element.

callback callback function:

The callback function can have three parameters. The following three parameters are introduced:

1.responseTxt: contains the result content when the call is successful.
2.statusTXT: contains the state of the call.
3. xhr: XMLHttpRequest object.

Code example:


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="//www.ofstack.com/" />
<title> The home of the script </title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#bt").click(function(){
    $("#thediv").load("antzone.txt",function(responseTxt,statusTxt,xhr){
      if(statusTxt=="success"){
        alert(" Content loaded successfully! ");
      } 
      if(statusTxt=="error"){
        alert(" error :"+xhr.status+":"+xhr.statusText);
      } 
    });
  });
})
</script>
</head>
<body>
<div id="thediv"></div>
<input type="button" value=" See the effect " id="bt"/>
</body>
</html>

The above code implementation can pop up an error because the path is incorrect and the file cannot be found.

I hope this article is helpful for you to design jQuery program.


Related articles: