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> 元素中:
也可以把jQuery 選擇器添加到URL 參數。
下面的例子把"demo_test.txt" 文件中id="p1" 的元素的內容,加載到指定的<div> 元素中:
可選的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);
});
});
$("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("外部内容加载成功!");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});
嘗試一下»