jQuery `.load()` 方法支援在 URL 後附加選擇器,僅提取回應 HTML 中匹配的片段插入目標元素,實現真正的「局部刷新」。
$('#targetElement').load('https://example.com/page.html #content > *');
url:請求地址selector:空格分隔,jQuery 選擇器,僅保留匹配元素的內容(不含外層標籤).load(url, callback) 或 .load(url, data, callback)
function refreshPanel() {
const url = 'https://api.example.com/dashboard?_' + Date.now(); // 防快取
$('#dashboard-panel').load(url + ' #panel-content > *', (response, status, xhr) => {
if (status === 'error') {
console.error('載入失敗:', xhr.status, xhr.statusText);
// 可顯示錯誤提示、重試按鈕
}
});
}
// 每 30 秒刷新一次
setInterval(refreshPanel, 30000);
// 首次載入
refreshPanel();
$('#result').load('/search', {q: 'keyword', page: 2}, (res, status) => {
if (status === 'success') console.log('搜尋完成');
});
$('#target').html('載入中...')
.load('/content #main', () => {
// 完成後移除 loading 或顯示動畫
});
function loadWithRetry(url, selector, retries = 3, delay = 1000) {
return $('#target').load(url + ' ' + selector)
.fail((xhr, status) => {
if (retries > 0) {
setTimeout(() => loadWithRetry(url, selector, retries - 1, delay * 2), delay);
} else {
$('#target').html('載入失敗,請稍後重試');
}
});
}