This question already has an answer here:
If I am on a page such as
http://somesite.com/somepage.php?param1=asdf
In the JavaScript of that page, I would like to set a variable to the value of the parameter in the GET part of the URL.
So in JavaScript:
<script>
param1var = ... // ... would be replaced with the code to get asdf from URI
</script>
What would "..." be?
I made this variation of gnarf's solution, so the call and the result is similar to PHP:
But as being called in a function slows the process, its better to use as global:
window['
var_name'] = decodeURIComponent( /
var_in_get=([^&#=]*)/.exec(window.location.search)[1] );
UPDATE
As I'm still learning JS, I created a better answer in a more JS behaviour:
This allows to be called just using
Url.get
.Example The url
?param1=param1Value¶m2=param2Value
can be called like:here is a snipet:
You don't need to do anything special, actually. You can mix JavaScript and PHP together to get variables from PHP straight into JavaScript.
Using jquery? I've used this before: http://projects.allmarkedup.com/jquery_url_parser/ and it worked pretty well.
Here is a version that JSLint likes:
Or if you need support for several values for one key like eg. ?key=value1&key=value2 you can use this:
Here's some sample code for that.
This looked ok:
From http://www.netlobo.com/url_query_string_javascript.html