JS之變更URL的傳參但不刷新頁(yè)面
需求:變更URL的傳參但不刷新頁(yè)面
代碼如下:
// 解析URL參數(shù)為對(duì)象 function getUrlParams() { const params = {}; const search = window.location.search.substring(1); if (search) { search.split('&').forEach(pair => { const [key, value] = pair.split('='); if (key) { params[key] = decodeURIComponent(value || ''); } }); } return params; } // 將參數(shù)對(duì)象轉(zhuǎn)換為URL查詢(xún)字符串 function paramsToQueryString(params) { const pairs = []; for (const key in params) { if (params.hasOwnProperty(key) && params[key] !== undefined) { pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`); } } return pairs.length ? `?${pairs.join('&')}` : ''; } // 更新URL參數(shù)(保留歷史記錄) function updateUrlParams(newParams, shouldReplace = false) { // 獲取當(dāng)前參數(shù) const currentParams = getUrlParams(); // 合并新參數(shù)到當(dāng)前參數(shù) const updatedParams = { ...currentParams, ...newParams }; // 構(gòu)建新的URL const newUrl = `${window.location.pathname}${paramsToQueryString(updatedParams)}${window.location.hash}`; // 更新URL而不刷新頁(yè)面 if (shouldReplace) { // 替換當(dāng)前歷史記錄 window.history.replaceState(updatedParams, '', newUrl); } else { // 添加新的歷史記錄 window.history.pushState(updatedParams, '', newUrl); } return updatedParams; } // 示例用法 // 添加或修改參數(shù),保留歷史記錄 updateUrlParams({ page: '2', sort: 'price' }); // 替換參數(shù),不保留歷史記錄 updateUrlParams({ filter: 'active' }, true); // 移除參數(shù)(設(shè)置為undefined) updateUrlParams({ sort: undefined }); // 監(jiān)聽(tīng)歷史記錄變化 window.addEventListener('popstate', (event) => { console.log('URL參數(shù)變化:', event.state); // 在這里可以根據(jù)新的參數(shù)更新頁(yè)面內(nèi)容 });
這種方法非常適合單頁(yè)應(yīng)用 (SPA),可以在不刷新頁(yè)面的情況下更新 URL 狀態(tài),同時(shí)保持瀏覽器的前進(jìn) / 后退功能正常工作。
使用 popstate 事件監(jiān)聽(tīng)用戶(hù)通過(guò)后退 / 前進(jìn)按鈕導(dǎo)致的 URL 變化

浙公網(wǎng)安備 33010602011771號(hào)