Javascript witchery: Passing parameters between pages with query string
Page: prev. | 1 | next
Q. Can Javascript be used to pass data between pages?
A. Yes. Javascript can access the query string, which is how the HTML Form element passes parameters using the GET method. A query string (or querystring) is appended to a URL with a questionmark followed by a series of fields and values, as in the example below:
?field1=value1&field2=value2&field3=value3
To access the query string use Javascript's location.search property.
qs = document.location.search;
In the example above, the variable qs
would now contain the entire query string, including the question mark. To make using the data passed easier the
question mark could be stripped and the fields and values split and stored in an array using Javascript's split method:
var qs = document.location.search; var qsArray = new Array(); //Strip first character from string. qs = qs.substring(1); //Split string by the ampersand char. qsArray = qs.split('&');
The zero-based array now contains three items.
//Output first field and value. document.write(qsArray[0]);
Using the document.write method on the arrays first item outputs field1=value1
.
As for passing the query string to a page, simply append the query string to the a URL and direct to that URL with the location.href
property.
var loadURL = 'http://domain.com'; var qs = '?field1=value1&field2=value2&field3=value3'; document.location.href = loadURL + qs;
Simply magic, huh?
There is a limitation and a beware with using the GET method however. Browsers may limit the number of characters in a URL (to which the query string is appended).
As for the beware …
Page: prev. | 1 | next