简体   繁体   English

Javascript:如何将变量附加到网址?

[英]Javascript: how can I append variables to the url?

how can I append variables to an URL with javascript without navigating to the url ? 如何在不导航到URL的情况下使用javascript将变量附加到URL?

thanks 谢谢

To append variables to the hash (as Matthew suggested ), you can do the following in plain JavaScript: 要将变量附加到散列(如Matthew建议的那样 ),您可以在纯JavaScript中执行以下操作:

window.location.hash = 'varA=some_value;varB=some_value';

This will add #varA=some_value;varB=some_value to your URL. 这会将#varA=some_value;varB=some_value到您的URL。 It will not refresh the page unless the hash value is equal to an anchor name or an element id within the document. 除非哈希值等于文档中的锚名称或元素id,否则它不会刷新页面。

Then to check if a hash value is present, simply do the following: 然后检查是否存在哈希值,只需执行以下操作:

var i, variables = window.location.hash.split(';');

if (variables.length > 0) {
    // Variables present in hash
    for (i = 0; i < variables.length; i++) {
       keyValuePair = variables.split('=');
       // keyValuePair[0] would be the key (variable name)
       // keyValuePair[1] would be the value
    }
}
else {
    // No variables in the hash
}

You may also want to check out the following Stack Overflow post on issues related to the URL encoding of the hash part in different browsers: 您可能还想查看以下Stack Overflow帖子,了解与不同浏览器中哈希部分的URL编码相关的问题:

You can modify window.location.hash . 您可以修改window.location.hash Anything else will cause a navigation. 其他任何东西都会导致导航。

I am not sure about that, but how is it with this?: 我不确定,但这是怎么回事?:

document.url + myVar + 'myString';

Though Javascript is not my language :P 虽然Javascript不是我的语言:P

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM