萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 局部頁面刷新技巧:利用 .load() 實現無刷新更新 DOM 片段

核心技巧:`.load(url selector)`

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();

進階用法

攜帶參數與 POST 請求


$('#result').load('/search', {q: 'keyword', page: 2}, (res, status) => {
  if (status === 'success') console.log('搜尋完成');
});

載入前顯示 Loading 狀態


$('#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('
載入失敗,請稍後重試
'); } }); }

注意事項與限制

  • 同源策略:跨域請求需後端配置 CORS 或使用代理。
  • 腳本執行:載入片段中的 `
copyright © 萬盛學電腦網 all rights reserved