...

View Full Version : query strings in javascript



cra992
06-02-2005, 07:52 PM
how do i retrieve parameters in html from a link such as: http://mysite.com/?param=1
does anyone know how to retrieve that information in javascript?

rlemon
06-02-2005, 09:40 PM
function getE(){
var url_string = String(document.location);
var url_array1 = url_string.split('?');
if(url_array1[1]){
var e_array = url_array1[1].split('&');
for(i=0;i<=(e_array.length);i++){
if(e_array[i]){
var useVal = e_array[i].split('=');
alert(useVal[0]+" == "+useVal[1]);// output
}
}
}
}


edit:

ok, this loops through the url pulling all variables (useVal[0]) and all values corresponding to those variables (useVal[1]).

Remember though, it does this in the order in which they appear.

so in the example:

/editpost.php?do=editpost&p=316287

in order it would alert:

do == editpost
p == 316287

SpirtOfGrandeur
06-02-2005, 10:52 PM
using rlemon's code...



function getE(){
var url_string = String(document.location);
var url_array1 = url_string.split('?');
var tObject = new Object();
if(url_array1[1]){
var e_array = url_array1[1].split('&');
for(i=0;i<=(e_array.length);i++){
if(e_array[i]){
var useVal = e_array[i].split('=');
if ( useVal.length == 2 ) {
tObject[useVal[0].toLowerCase()] = useVal[1];
}
}
}
}
return tObject;
}


If you call
qStr = getE();

You can get from the string;
/editpost.php?do=editpost&p=316287
qStr['do'] = editpost;
qStr['p'] = 316287

But
qStr['Do'] = undefined

cra992
06-03-2005, 03:28 AM
how do i display whats after the ?param=

rlemon
06-03-2005, 07:10 AM
are you not looking at the example?

ok, here's a tip.

if you are returning text, you use innerHTML with a span tag.

this is done as follows:



function getE(){
var url_string = window.location.href;
var url_array1 = url_string.split('?');
if(url_array1[1]){
var e_array = url_array1[1].split('&');
for(i=0;i<=(e_array.length);i++){
if(e_array[i]){
var useVal = e_array[i].split('=');
if(useVal[0] == "param"){
var output = document.getElementById('span_id');
output.innerHTML = useVal[1];
}
}
}
}
}


then in the html



<p>
blah blah blah this is some text, hey you want to know what param is?<br />
Why yes, yes i do want to know!<br />
well, param = <span id="span_id"></span>!<br />
YAY!
</p>

glenngv
06-03-2005, 09:20 AM
http://www.codingforums.com/showthread.php?t=25786



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum