序列化对象以在 JavaScript/jQuery 中查询字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3308846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:06:04  来源:igfitidea点击:

Serialize object to query string in JavaScript/jQuery

javascriptjqueryserializationquery-string

提问by Tomas Aschan

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).

我正在尝试查找有关如何将对象序列化以查询字符串格式的信息,但我所有的搜索都淹没在有关如何使用其他方式(字符串/表单/任何 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...

有没有好的方法可以做到这一点?我不介意插件或诸如此类的东西-如果我找到的代码不是插件,我可能会无论如何将其重写为一个...

回答by Chris Laplante

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

你想要$.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"}

$.paramwill return this:

$.param将返回:

a=1&b=23&c=te!%40%23st

回答by Rich Smith

For a quick non-JQuery function...

对于快速的非 JQuery 函数...

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.

请注意,这不处理数组或嵌套对象。

回答by wprl

Another option might be node-querystring.

另一种选择可能是node-querystring

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

它在npm和中都可用bower,这就是我一直在使用它的原因。

回答by Alex Stetsenko

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

或者 YUI 有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);