jQuery - AJAX load() 方法
jQuery load() 方法
load() 方法從服務(wù)器加載數(shù)據(jù),并把返回的數(shù)據(jù)放入被選元素中。
語法:
$(selector).load(URL,data,callback);
必需的?URL?參數(shù)規(guī)定您希望加載的 URL。
可選的?data?參數(shù)規(guī)定與請求一同發(fā)送的查詢字符串鍵/值對集合。
可選的?callback?參數(shù)是 load() 方法完成后所執(zhí)行的函數(shù)名稱。
這是示例文件("demo_test.txt")的內(nèi)容:
<h2>jQuery AJAX 是個非常棒的功能!</h2> <p id="p1">這是段落的一些文本。</p>
把文件 "demo_test.txt" 的內(nèi)容加載到指定的 <div> 元素中:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</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 修改文本內(nèi)容</h2></div> <button>獲取外部內(nèi)容</button> </body> </html>
也可以把 jQuery 選擇器添加到 URL 參數(shù)。
例子把 "demo_test.txt" 文件中 id="p1" 的元素的內(nèi)容,加載到指定的 <div> 元素中:
<!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>
可選的 callback 參數(shù)規(guī)定當(dāng) load() 方法完成后所要允許的回調(diào)函數(shù)?;卣{(diào)函數(shù)可以設(shè)置不同的參數(shù):
responseTxt?- 包含調(diào)用成功時的結(jié)果內(nèi)容
statusTXT?- 包含調(diào)用的狀態(tài)
xhr?- 包含 XMLHttpRequest 對象
下面的例子會在 load() 方法完成后顯示一個提示框。如果 load() 方法已成功,則顯示"外部內(nèi)容加載成功!",而如果失敗,則顯示錯誤消息:
<!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("外部內(nèi)容加載成功!"); if(statusTxt=="error") alert("Error: "+xhr.status+": "+xhr.statusText); }); }); }); </script> </head> <body> <div id="div1"><h2>使用 jQuery AJAX 修改該文本</h2></div> <button>獲取外部內(nèi)容</button> </body> </html>
完整實例:
先創(chuàng)建一個text.html文件:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <div class="comment"> 已有評論: </div> <div class="comment"> <h6>張三:</h6> <p class="para">沙發(fā)。</p> </div> <div class="comment"> <h6>李四:</h6> <p class="para">板凳。</p> </div> <div class="comment"> <h6>王五:</h6> <p class="para">地板。</p> </div> </body> </html>
在創(chuàng)建另一個HTML文件(名稱可以隨意?。懭雑Query?AJAX ??load() 方法:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#send").click(function(){ $("#resText").load("text.html"); //引入text.html文件。 }); }); </script> </head> <body> <input type="button" id="send" value="Ajax獲取" /> <div id="resText"></div> </body> </html>