$(selector).load(url, [data], [callback]);
// url: 請求地址
// data: 可選,發送給服務端的參數(對象/查詢字符串),有值則自動變為 POST 請求
// callback: 可選,請求完成後執行,參數 (responseText, textStatus, jqXHR)
// 1. 無參數 GET
$('#myID').load('test.php');
// 2. 單參數 POST (自動轉 POST)
$('#myID').load('test.php', {name: 'Adam'});
// 3. 多參數 POST
$('#myID').load('test.php', {name: 'Adam', site: '61dh.com'});
// 4. 數組參數
$('#myID').load('test.php', {'myinfo[]': ['Adam', '61dh.com']});
// 服務端接收到 myinfo 數組
注意:有 data 參數時默認發送 POST** 請求,服務端需用 $_POST (PHP) 或 request.POST (Django) 等獲取。
$('#go').click(function() {
$('#myID').load('welcome.php', {lname: 'Cai', fname: 'Adam'}, function(response, status, xhr) {
if (status === 'success') {
$('#myID').fadeIn('slow'); // 內容加載完成後淡入
} else {
$('#myID').html('加載失敗: ' + xhr.status);
}
});
});
// 全局關閉
$.ajaxSetup({cache: false});
// 單次請求加時間戳
$('#myID').load('test.php?' + Date.now());
// 或服務端設置頭
// header("Cache-Control: no-cache, must-revalidate");
// 僅加載 test.html 中 id="a" 的元素及其內容
$('body').load('test.html #a');
// 空格後跟 jQuery 選擇器,極其實用!
原理:jQuery 獲取完整 HTML 後,用選擇器過濾提取片段再插入目標容器。
.load() 返回的 HTML 中的 <script> 標籤不會執行(jQuery 內部用 .html() 設置,會過濾腳本)。需在回調中手動 eval 或改用 .ajax() + dataType:'html' 自行處理。.load() 是 .ajax() 的簡便封裝,適合「加載片段並插入容器」的簡單場景。複雜交互(需執行腳本、錯誤處理、請求攔截)請直接用 $.ajax() 或 fetch。