You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用原生JS阻止表单提交时如何同步搜索参数到URL实现可分享链接

解决方案

你调用event.preventDefault()后,浏览器默认的表单提交跳转逻辑被终止,因此不会自动携带参数更新地址栏,可通过原生History API手动修改URL,该操作不会触发页面刷新。

修改后的代码实现

searchKeywordForm.addEventListener('submit', async (event) => {
    event.preventDefault();

    //Clear all courseItems and start from scratch
    courseItems = [];
    courseContainerElement.innerHTML = "";
    let searchInput = document.getElementById("keywords");
    const keyword = searchInput.value;
    
    // 新增:更新地址栏查询参数
    const searchParams = new URLSearchParams(window.location.search);
    searchParams.set('keywords', keyword);
    const newUrl = `${window.location.pathname}?${searchParams.toString()}`;
    // 如需替换当前历史记录而非新增,可改为 history.replaceState
    history.pushState({ path: newUrl }, '', newUrl);

    await fetchDataByKeywords(keyword);
})

注意事项

  • 使用URLSearchParams处理参数会自动完成特殊字符转义,无需手动处理中文、符号等场景的URL格式问题
  • 如果不需要保留搜索历史记录,可将pushState替换为replaceState,避免用户多次点击后退才能离开当前页面
  • 如需支持用户点击浏览器前进/后退按钮自动对应搜索结果,可额外监听popstate事件,读取当前URL参数后重新触发搜索逻辑即可

内容的提问来源于stack exchange,提问作者Xavier Ong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 15:54:03