jQuery - AJAX load() 方法
jQuery load() 方法
jQuery load() 方法是簡單但強大的 AJAX 方法。
load() 方法從伺服器加載數據,並把返回的數據放入被選元素中。
語法:
$(selector).load(URL,data,callback);
必需的 URL 參數規定您希望加載的 URL。
可選的 data 參數規定與請求一同發送的查詢字串鍵/值對集合。
可選的 callback 參數是 load() 方法完成後所執行的函數名稱。
這是示例檔("demo_test.txt")的內容:
<h2>jQuery AJAX 是個非常棒的功能!</h2>
<p id="p1">這是段落的一些文本。</p>
下麵的例子會把檔 "demo_test.txt" 的內容加載到指定的 <div> 元素中:
實例
$("#div1").load("demo_test.txt");
也可以把 jQuery 選擇器添加到 URL 參數。
下麵的例子把 "demo_test.txt" 檔中 id="p1" 的元素的內容,加載到指定的 <div> 元素中:
實例
$("#div1").load("demo_test.txt #p1");
可選的 callback 參數規定當 load() 方法完成後所要允許的回調函數。回調函數可以設置不同的參數:
- responseTxt - 包含調用成功時的結果內容
- statusTXT - 包含調用的狀態
- xhr - 包含 XMLHttpRequest 對象
下麵的例子會在 load() 方法完成後顯示一個提示框。如果 load() 方法已成功,則顯示"外部內容加載成功!",而如果失敗,則顯示錯誤消息:
實例
$("button").click(function(){
$("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("外部內容加載成功!");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});