Many online applications, from search engines to RSS readers and aggregators, including Yahoo! Pipes and in programming on-offline mashups use URL query strings and parameters.
This article looks at:
Firstly, however, it is necessary to look at an example of a query string, and how it can be used as a URL.
A query string is simply a piece of text which describes a structured query, as a plain text string, which can be passed to another service, application, or web site. It might look like the following:
In the above example, designed for use with URL query strings, there is only a single parameter. It is snipped from the standard Google URL query string:
More parameters can be added to the URL query string by separating them with the '&' sign. Each one should be constructed from a parameter and a value, separated by an '=' sign. The target for the query string is a URL, in this case:
However, script enabled pages can also be used to good effect, allowing a certain level of interactivity. To do this, the receiving page needs to be able to extract the URL query string parameters, using, for example, JavaScript.
In order to extract the parameters, there are two operations to perform on the URL query string:
Luckily, there is an excellent function called split in JavaScript that deals with the simplest types of URL query string. Before using it, it is necessary to obtain the URL:
This code simply returns a string encoding of the URL. Next, a simple call to .split will enable the script to obtain everything after the '?' as an array:
This leaves the root (up to the ?) in query_string[0] and the parameters, as a '&' separated string of tuples, in query_string[1]. The .split function can then be used again to deliver an array of tuples:
Now, each of the params can be extracted by a simple .split on the relevant element in the array:
This could be placed in a loop, and then each item evaluated for first the name, stored in param_item[0] and then the value, stored in patam_item[1]. However, it would be much better to store these as an associative array, by looping through the params array and assigning them thus:
The unescape call has been added to remove URL escaping from the query string. By placing the values in an associative array, the programmer is then free to extract known values by name:
Using the above techniques, the programmer should be able to build URL query strings for use with any online service that accepts them. For example, the Google query string has many different URL parameters that can be used for custom searches. The code provdied here can also be used to allow users to specify parameters that can then be supplied to custom JavaScript or AJAX pages to provide query string interactivity with ease.