The Hypertext Transfer Protocol (HTTP) defines three methods to send data to a server — GET, POST, and PUT. GET requests append their data to the end of the URL in the form of a list of key–value pairs known as a query string — for example:
http://example.com/?key1=value1&key2=value2
In JavaScript this part of the URL can be accessed easily through the location.search property. However, naïve attempts to parse and decode this information often fail to take into account several issues — for example, the same key may occur multiple times, spaces may be encoded either as plus signs or the escape sequence %20, and semicolons may be used as separators instead of ampersands. QueryData handles these issues and makes the GET data available in a convenient format.
Download QueryData
Download one of the files below and upload it to your web server.
File | Size | Description |
---|---|---|
QueryData.js | 2,568 bytes | Full version, with comments |
QueryData.compressed.js | 689 bytes | Compressed version |
Link to the file using a script element in the head of your page:
1 |
|
Using QueryData
To access the GET data from the page URL’s query string, create a new instance of QueryData with no parameters:
1 2 |
|
The object that is returned has as its keys and values the keys and values from the GET data. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
QueryData isn’t limited just to parsing the page URL’s query string. An alternative query string can be passed as a parameter:
1 2 |
|
Handling duplicate keys
A key may occur multiple times in a query string (for example, as a result of a form containing a ‘select’ element with the ‘multiple’ attribute set). By default, QueryData overwrites earlier values with later values for the same key, but setting its optional second parameter to ‘true’ causes it instead to create an array of values for each key:
1 2 3 4 5 6 7 8 9 |
|