jQuery load() method
jQuery - AJAX load() method
jQuery load() method
jQuery load() method Is a simple but powerful AJAX method.
The load() method loads data from the server and puts the returned data into the selected element.
Syntax:
Required URL parameters specify the URL you wish to load .
The optional data parameter specifies the set of query string key/value pairs sent with the request.
The optional callback parameter is the name of the function executed after the load() method is completed.
This is the content of the sample file ("demo_test.txt"):
<p id="p1">This is some text of the paragraph. </p>
The following example will load the contents of the file "demo_test.txt" into the specified <div> element:
Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("#div1").load("/try/ajax/demo_test.txt"); }); }); </script> </head> <body> <div id="div1"><h2>使用 jQuery AJAX 修改文本内容</h2></div> <button>获取外部内容</button> </body> </html>
Run Example»
Click the "Run Example" button to view the online example
You can also add the jQuery selector to the URL parameter.
The following example loads the content of the element with id="p1" in the "demo_test.txt" file into the specified <div> element:
Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("#div1").load("/try/ajax/demo_test.txt #p1"); }); }); </script> </head> <body> <div id="div1"><h2>使用 jQuery AJAX 修改文本</h2></div> <button>获取外部文本</button> </body> </html>
Run instance»
Click the "Run instance" button to view the online instance
The optional callback parameter specifies when load( ) callback function to allow after the method completes. The callback function can set different parameters:
responseTxt - contains the result content when the call is successful statusTXT - contains the status of the call xhr - contains the XMLHttpRequest object
The following example will be completed in the load() method A prompt box is then displayed. If the load() method has succeeded, "External content loaded successfully!" is displayed, and if it fails, the error message is displayed:
Instance
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("#div1").load("/try/ajax/demo_test.txt",function(responseTxt,statusTxt,xhr){ if(statusTxt=="success") alert("外部内容加载成功!"); if(statusTxt=="error") alert("Error: "+xhr.status+": "+xhr.statusText); }); }); }); </script> </head> <body> <div id="div1"><h2>使用 jQuery AJAX 修改该文本</h2></div> <button>获取外部内容</button> </body> </html>
Run Instance»
Click the "Run Instance" button to view the online instance