将参数附加到 URL 而不刷新

问题描述 投票:0回答:6

我知道这个问题之前已经被问过很多次了,但答案的描述性不足以解决我的问题。我不想更改页面的整个 URL。我想在单击按钮时附加一个参数

&item=brand
而不刷新。

使用

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

使用

window.location.hash = "&item=brand";
追加而不刷新,但使用哈希
#
消除了参数的使用/效果。我尝试在附加后删除哈希,但这不起作用。


这个答案和许多其他人建议使用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。或者如何为相同目的设置片段标识符。一个好的教程、演示或带有一点解释的代码就太好了。

演示我到目前为止所做的事情。我们将非常感谢您的回答。

javascript jquery html pushstate html5-history
6个回答
182
投票

您可以使用 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);

56
投票

如果您想同时添加和删除参数,也可以使用 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

31
投票

如果有人想向更复杂的网址添加参数(我的意思是,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);

希望这有帮助!


1
投票

修改了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);
    }
}

1
投票

如果您想在当前网址中附加多个参数而不重新加载页面,请尝试以下操作:

window.history.replaceState(null, null, `?${$.param({
   item: 'brand',
   lang: 'en',
})}`);

$.param
会将您的对象转换为
item=brand&lang=en
,然后只需在开头添加
?

结果将是:

httpts://app.com/index?item=brand&lang=en


0
投票

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}`)
    : "";
}

© www.soinside.com 2019 - 2024. All rights reserved.