\'bar\',
\'baz\'=>\'boom\',
\'cow\'=>\'milk\',
\'php\'=>\'hypertext processor\');
If you're using jQuery, then you can use the jQuery.param() function:
var obj = { "foo":"bar", "baz":"boom", "php":"hypertext processor" };
var str = jQuery.param(obj);
alert(str); // should be "foo=bar&baz=boom&php=hypertext+processor"
It can serialise some complex arrays too.
Try the jQuery query plugin. It's pretty intuitive. You can use get and set accessors to read and modify the query string:
var cow = $.query.get('cow');
$.query.set('cow', 'goat');
You can create a new query object from an existing string:
var fromVar = $.query.load('?cow=milk')
var cow = fromVar.get('cow'); // milk
You can also create an empty object:
var newQ = $.query.empty();
newQ = newQ.set('first', 'value'); // "?first=value"
You can use the URLSearchParams
class:
var searchParametersData = {
"foo": "baz",
"bar": "foo"
};
var searchParameters = new URLSearchParams();
Object.keys(searchParametersData).forEach(function(parameterName) {
searchParameters.append(parameterName, searchParametersData[parameterName]);
});
console.log(searchParameters.toString()); // foo=baz&bar=foo
To get the parameters object from a search parameter string, use this:
var searchParametersString = "foo=baz&bar=foo";
var searchParameters = new URLSearchParams(searchParametersString);
var searchParametersData = {};
for (var searchParameter of searchParameters) {
searchParametersData[searchParameter[0]] = searchParameter[1];
}
console.log(searchParametersData); // {foo: "baz", bar: "foo"}