Serialize object to query string in JavaScript/jQu

2019-01-04 06:48发布

This question already has an answer here:

I'm trying to find information on how to serialize an object to query string format, but all my searches are drowning in results on how to go the other way (string/form/whatever to JSON).

I have

{ one: 'first', two: 'second' }

and I want

?one=first&two=second

Is there a good way to do this? I don't mind plugins or whatnots - if the code I find is not a plugin, I'll probably re-write it to one anyway...

4条回答
贼婆χ
2楼-- · 2019-01-04 07:13

Another option might be node-querystring.

It's available in both npm and bower, which is why I have been using it.

查看更多
叛逆
3楼-- · 2019-01-04 07:14

For a quick non-JQuery function...

function jsonToQueryString(json) {
    return '?' + 
        Object.keys(json).map(function(key) {
            return encodeURIComponent(key) + '=' +
                encodeURIComponent(json[key]);
        }).join('&');
}

Note this doesn't handle arrays or nested objects.

查看更多
Evening l夕情丶
4楼-- · 2019-01-04 07:37

You want $.param(): http://api.jquery.com/jQuery.param/

Specifically, you want this:

var data = { one: 'first', two: 'second' };
var result = $.param(data);

When given something like this:

{a: 1, b : 23, c : "te!@#st"}

$.param will return this:

a=1&b=23&c=te!%40%23st
查看更多
劳资没心,怎么记你
5楼-- · 2019-01-04 07:37

Alternatively YUI has http://yuilibrary.com/yui/docs/api/classes/QueryString.html#method_stringify.

For example:

var data = { one: 'first', two: 'second' };
var result = Y.QueryString.stringify(data);
查看更多
登录 后发表回答