I currently have an associative array urlvalue with values as follows:
{"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"}
I would like to turn this array into a URL so that I can send the variables to another page. How can it be done using jquery so that they appear like this:
?folder=subscriber&file=setstatus&alert=yes&id=12
Thanks
You need jQuery.param() :
var params = {"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"};
var str = jQuery.param(params);
Use the
$.param(VALUE)
funciton.
Example:
var obj = {"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"},
toParam= $.param(obj);
alert(toParam);
output:
folder=subscriber&file=setstatus&alert=yes&id=12
Fillder: http://jsfiddle.net/BGjWT/
You can use the map
method to turn each key-value pair into a string, then join the array of strings into a single string. Use the encodeURICompontent
function to encode the keys and values correctly:
var urlvalue = {"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"};
var param = '?' + $.map(urlvalue, function(v, k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(v);
}).join('&');
alert(param);
You can use the http_build_query()
function:
Try this:
var test = {"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"};
var queryString = "?folder=" + test.folder + "&file=" + test.file + "&alert=" + test.alert + "&id=" + test.id + "";
alert(queryString);
Possible solution that does not involve jQuery at all (I assume people post jQuery solutions because of the tag):
var combine = function(params) {
var lst = [];
for (var key in params) {
if (params.hasOwnProperty(key)) {
lst.push(encodeURIComponent(key)+"="+encodeURIComponent(params[key]));
}
}
return "?"+lst.join("&");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.