简体   繁体   中英

Javascript: how can I append variables to the url?

how can I append variables to an URL with javascript without navigating to the url ?

thanks

To append variables to the hash (as Matthew suggested ), you can do the following in plain JavaScript:

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

This will add #varA=some_value;varB=some_value to your URL. It will not refresh the page unless the hash value is equal to an anchor name or an element id within the document.

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:

You can modify 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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