How to implement something like PHP's http_build_query and the reverse in javascript?
<?php
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data);
/* Output:
foo=bar&baz=boom&cow=milk&php=hypertext+processor
*/
How to do similar thing in javascript,say, get the query string from the array ,and convert the array to query string?
UPDATE
the jquery plugin is not working:
var fromVa开发者_运维知识库r = $.query.load('?cow=milk')
fromVar.set('first', 'value');
fromVar.toString()
It outputs ?cow=milk
while I want it to be ?cow=milk&first=value
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.
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"}
Nowadays, you can simply use the URLSearchParams
constructor on your object.
const data = {
"test1": 1,
"test2": "two",
"test3": 3,
};
const params = new URLSearchParams(data);
console.log(params.toString());
I use following javascript counterpart of PHP's http_build_query:
Function definition:
const http_build_query = (dataToSend) => {
let formBody = []
for (let key in dataToSend) {
let encodedKey = encodeURIComponent(key)
let encodedValue = encodeURIComponent(dataToSend[key])
formBody.push(encodedKey + '=' + encodedValue)
}
return formBody.join('&')
}
Usage:
let dataToSend = {user_id:123, name:'Your name'}
const formBody = http_build_query(dataToSend)
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"
精彩评论