简体   繁体   English

jQuery-从关联数组创建URL

[英]Jquery - Create URL from an associative array

I currently have an associative array urlvalue with values as follows: 我目前有一个关联数组urlvalue ,其值如下:

{"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. 我想将此数组转换为URL,以便可以将变量发送到另一个页面。 How can it be done using jquery so that they appear like this: 如何使用jquery使其显示如下:

?folder=subscriber&file=setstatus&alert=yes&id=12

Thanks 谢谢

You need jQuery.param() : 您需要jQuery.param()

var params = {"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"};
var str = jQuery.param(params);

Use the 使用

$.param(VALUE) $ .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 folder = subscriber&file = setstatus&alert = yes&id = 12

Fillder: http://jsfiddle.net/BGjWT/ 填写人: 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. 您可以使用map方法将每个键值对转换为字符串,然后将字符串数组连接为单个字符串。 Use the encodeURICompontent function to encode the keys and values correctly: 使用encodeURICompontent函数正确编码键和值:

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.net/Guffa/sCn5U/ 演示: http//jsfiddle.net/Guffa/sCn5U/

You can use the http_build_query() function: 您可以使用http_build_query()函数:

http://phpjs.org/functions/http_build_query/ http://phpjs.org/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 小提琴

如果您不介意使用插件, 可以使用一些不错的插件

Possible solution that does not involve jQuery at all (I assume people post jQuery solutions because of the tag): 根本不涉及jQuery的可能解决方案(由于标签,我认为人们发布了jQuery解决方案):

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("&");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM