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
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
Share Improve this question asked Aug 8, 2013 at 11:35 Stanley NgumoStanley Ngumo 4,2498 gold badges48 silver badges65 bronze badges 1- 1 This looks like a homework. What have you tried? – freakish Commented Aug 8, 2013 at 11:39
7 Answers
Reset to default 8You 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/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);
Demo: http://jsfiddle/Guffa/sCn5U/
You can use the http_build_query()
function:
http://phpjs/functions/http_build_query/
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);
Fiddle
If you don't mind using a plugin, there are some nice ones that do the job.
Possible solution that does not involve jQuery at all (I assume people post jQuery solutions because of the tag):
var bine = function(params) {
var lst = [];
for (var key in params) {
if (params.hasOwnProperty(key)) {
lst.push(encodeURIComponent(key)+"="+encodeURIComponent(params[key]));
}
}
return "?"+lst.join("&");
}