I would like to append an associative array to a URL’s query string. For whatever reason, there is no native javascript method to accomplish this task. This needs to be done manually or using a common web framework such as jQuery.
The first step is to serialize the associative array into a query string,
native javascript
With plain-old-javascript, you can do something like this,
var queryVars = {'foo':'bar', 'spam':'eggs', 'tracker':'yes' }; var queryStringParts = new Array(); for(var key in queryVars) { queryStringParts.push(key + '=' + queryVars[key]); } var queryString = queryStringParts.join('&');
The value of queryString will be
foo=bar&spam=eggs&tracker=yes
jQuery
Since version 1.2 jQuery has supported the jQuery.param() function to serialize any array or object into a URL query string. The above example becomes,
var queryVars = {'foo':'bar', 'spam':'eggs', 'tracker':'yes' }; var queryString = jQuery.param(queryVars);
node.js
My favorite approach is the node.js querystring.stringify() function, I like this as it is easiest to remember,
var queryVars = {'foo':'bar', 'spam':'eggs', 'tracker':'yes' }; var queryString = querystring.stringify(queryVars);
Appending ? or &
In most cases you don’t want to assume an input url does not already contain a query string, in fact, this would be a rather bad assumption. To get this to work you’ll want to append your new query string to any existing query string using the & character, otherwise use the ? character. Here is an example,
function appendQueryString(url, queryVars) { var firstSeperator = (url.indexOf('?')==-1 ? '?' : '&'); var queryStringParts = new Array(); for(var key in queryVars) { queryStringParts.push(key + '=' + queryVars[key]); } var queryString = queryStringParts.join('&'); return url + firstSeperator + queryString; } var url = "something.html?q=test"; var queryVars = {'foo':'bar', 'spam':'eggs', 'tracker':'yes' }; var new_url = appendQueryString(url, queryVars);
The value of new_url will be
something.html?q=test&foo=bar&spam=eggs&tracker=yes