【问题标题】:urlSearchParams not updating the urlurlSearchParams 不更新 url
【发布时间】:2022-11-23 18:58:32
【问题描述】:

我正在尝试将搜索和页面添加到我的网址,以便在页面上进行搜索和分页。

 const urlParams = new URLSearchParams(window.location.search);
if(!urlParams.has('search'){
   urlParams.append('search', question);
}
if(!urlParams.has('page'){
   urlParams.append('page', pageIndex);
}

这似乎对实际网址没有任何作用。 但是当我调用 urlParams.toString() 然后我可以看到它们已被添加,但它们不在浏览器的实际 url 中。

我使用的是 Chrome 107,所以它应该支持它。 我错过了什么吗?

到目前为止,文档对我没有帮助。

【问题讨论】:

    标签: javascript search pagination url-parameters urlsearchparams


    【解决方案1】:

    你可以试试这样:

    首先,检索当前的path。然后,将 urlParams 附加到检索到的路径并使用 history.pushState() 设置新的 URL。

    const question = "the question";
    const pageIndex = 3;
    
    const urlParams = new URLSearchParams(window.location.search);
    
    if (! urlParams.has('search')) {
       urlParams.append('search', question);
    }
    
    if (! urlParams.has('page')) {
       urlParams.append('page', pageIndex);
    }
    
    const path = window.location.href.split('?')[0];
    const newURL = `${path}?${urlParams}`;
    
    history.pushState({}, '', newURL);
    

    资料来源:

    【讨论】:

      【解决方案2】:

      当然它对实际 url 没有任何作用,您正在创建 URLParameters 选项并更新它。你缺少的是:

      window.loacation.search = urlParams.toString()
      

      它将更改浏览器 url 中的查询字符串并重新加载页面。 如果您对重新加载页面不感兴趣,可以使用history DOM 对象

      let url = new URL(window.location.href);
      if(!(url.searchParams.has('search'))){
         url.searchParams.append('search', question);
      }
      if(!(url.searchParams.has('page'))){
         url.searchParams.append('page', pageIndex);
      }
      history.pushState({},'',url.href);
      

      【讨论】:

        猜你喜欢
        • 2022-11-22
        • 2020-11-15
        • 2017-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-23
        • 1970-01-01
        • 2021-02-15
        相关资源
        最近更新 更多