So I have html page called A.html
it was called like this from B.html
: A.html?varString="bla-bla-bla"
Is it correct for sending args to JS? How to parse args from JS?
(not using any frameworks like Jquery, working in IE6, FireFox 3)
Here is a function to parse the query string. Pass it the parameter name and it returns the value.
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++)
{
var pair = vars[i].split("=");
if (pair[0] == variable)
{
return pair[1];
}
}
return -1; //not found
}
Use location.search
:
alert(location.search); // will display everything from the ? onwards
You probably want to separate the different variables from the query string so that you can access them by name:
var request = {};
var pairs = location.search.substring(1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
request[pair[0]] = pair[1];
}
Then you can access it like request['varString']
and that will give you "bla-bla-bla"
.
Mostly you'd like to handle the parameters passed to your page in the server side, but if you got your reasons why to do it client-side, here's a small script i found:
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
i didn't test it, but i'm pretty sure it'll to the job.
just use it like: gup('parameter')
and it'll return the parameter value for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With