【问题标题】:Appending parameter to URL without refresh将参数附加到 URL 而不刷新
【发布时间】:2015-12-26 00:00:24
【问题描述】:

我知道这个问题已经被问过很多次了,但答案的描述性不足以解决我的问题。我不想更改页面的整个 URL。我想在不刷新的情况下单击按钮时附加参数&item=brand

使用document.location.search += '&item=brand'; 会刷新页面。

使用window.location.hash = "&item=brand"; 追加而不刷新,但使用哈希# 消除参数的使用/影响。我尝试在附加后删除哈希,但没有奏效。


This answer 和许多其他人建议使用 HTML5 History API,特别是 history.pushState 方法,并且对于旧浏览器是设置片段标识符以防止页面重新加载。但是怎么做呢?


假设网址为:http://example.com/search.php?lang=en

如何使用 HTML5 pushState 方法或片段标识符附加 &item=brand,以便输出如下所示:http://example.com/search.php?lang=en&item=brand 而无需刷新页面?


我希望有人可以了解如何使用 HTML5 pushState 将参数附加到现有/当前 URL。或者,如何为相同目的设置片段标识符。一个好的教程、演示或带有一点解释的代码会很棒。

Demo 到目前为止我所做的事情。非常感谢您的回答。

【问题讨论】:

    标签: javascript jquery html pushstate html5-history


    【解决方案1】:

    您可以使用pushStatereplaceState 方法,即:

    window.history.pushState("object or string", "Title", "new url");
    

    window.history.replaceState(null, null, "?arg=123");
    

    带参数的示例:

    var refresh = window.location.protocol + "//" + window.location.host + window.location.pathname + '?arg=1';    
    window.history.pushState({ path: refresh }, '', refresh);
    

    【讨论】:

    • 非常感谢!那行得通,但令人惊讶的是,该参数并未应用于系统。但是,当我将其手动添加到 URL 中时,它会生效。我将把它作为一个公认的答案,因为它解决了我的主要问题,但是如果您对使用 history.pushState 添加参数时为什么不会将参数应用于系统有任何建议,请告诉我:) 再次感谢您。跨度>
    • 谢谢,我最终使用了 window.history.replaceState(null, null, "?mock");无需重新加载即可添加 url 参数。
    • 浏览器兼容性为somewhat good,但请注意,它不适用于 IE10 以下或(可能)某些移动浏览器。
    【解决方案2】:

    如果有人想将参数添加到更复杂的 url(我的意思是,https://stackoverflow.com/questions/edit?newParameter=1),以下代码对我有用:

    var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?newParameter=1';
    window.history.pushState({ path: newurl }, '', newurl);
    

    希望这会有所帮助!

    【讨论】:

    【解决方案3】:

    如果您想同时添加和删除参数,您也可以使用 URL API:

    const url = new URL(window.location.href);
    url.searchParams.set('param1', 'val1');
    url.searchParams.delete('param2');
    window.history.replaceState(null, null, url); // or pushState
    

    【讨论】:

      【解决方案4】:

      修改了Medhi 的答案,这成功了

      const insertParam = (key: string, value: string) => {
          key = encodeURIComponent(key);
          value = encodeURIComponent(value);
      
          let kvp = window.location.search.substr(1).split('&');
          if (kvp[0] === '') {
              const path = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + key + '=' + value;
              window.history.pushState({ path: path }, '', path);
      
          } else {
              let i = kvp.length; let x; while (i--) {
                  x = kvp[i].split('=');
      
                  if (x[0] === key) {
                      x[1] = value;
                      kvp[i] = x.join('=');
                      break;
                  }
              }
      
              if (i < 0) { 
                  kvp[kvp.length] = [key, value].join('=');
              }
      
              const refresh = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + kvp.join('&');  
              window.history.pushState({ path: refresh }, '', refresh);
          }
      }
      

      【讨论】:

        【解决方案5】:

        export function getHash(hash: string, key: string): string | undefined {
          return hash
            .split("#")
            .find((h) => h.startsWith(key))
            ?.replace(`${key}=`, "");
        }
        export function setHash(hash: string, key: string, value: string): string {
          let hashArray = hash.split("#").filter((h) => !h.startsWith(key));
          hashArray.push(`${key}=${value}`);
          return hashArray.length > 0
            ? hashArray.reduce((s1, s2) => `${s1}#${s2}`)
            : "";
        }
        export function deleteHash(hash: string, key: string): string {
          let hashArray = hash.split("#").filter((h) => !h.startsWith(key));
          return hashArray.length > 0
            ? hashArray.reduce((s1, s2) => `${s1}#${s2}`)
            : "";
        }

        【讨论】:

          猜你喜欢
          • 2020-03-06
          • 2017-11-25
          • 2014-07-10
          • 1970-01-01
          • 2019-07-09
          • 2012-05-13
          • 1970-01-01
          • 2015-04-22
          • 2012-09-05
          相关资源
          最近更新 更多