最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery - Create URL from an associative array - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

7 Answers 7

Reset to default 8

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/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("&");
}
发布评论

评论列表(0)

  1. 暂无评论