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:
- Encoding of window.location.hash
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
精彩评论