javascript 将数组作为查询字符串传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12829336/
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
Pass array as query string
提问by Jesse
I'm attempting to pass an array to my server via jsonp - here's a JSON example of what I'm trying to pass:
我正在尝试通过 jsonp 将数组传递到我的服务器 - 这是我试图传递的 JSON 示例:
["something","another_thing",4,{"iam" : "anobject"}]
However, I'm not sure how (if it's possible) to pass an array.
但是,我不确定如何(如果可能)传递数组。
I assumed it would be like this:
我以为它会是这样的:
something&another_thing&4&[iam]=anobject
but when I pass that to querystring.parse()
in node, it gives me this:
但是当我将它传递给querystring.parse()
节点时,它给了我这个:
{ '4': '',
something: '',
another_thing: '',
'[iam]': 'anobject' }
That's definitely not what I want. I can just use JSON, but this is now something I'm wondering if is possible.
那绝对不是我想要的。我可以只使用 JSON,但现在我想知道这是否可能。
回答by Quentin
If you want to pass that data structure using PHP's URI format (which is what your attempt looks like), it would look something like:
如果您想使用 PHP 的 URI 格式(这就是您尝试的格式)传递该数据结构,它看起来类似于:
data[0]=something&data[1]=another_thing&data[2]=4&data[3][iam]=anobject
You are probably better off just passing the JSON itself though. Take the JavaScript object and run it through JSON.stringify()
and encodeURIComponent()
to get:
不过,您最好只传递 JSON 本身。获取 JavaScript 对象并运行它JSON.stringify()
并encodeURIComponent()
得到:
data=something%2Canother_thing%2C4%2C%5Bobject%20Object%5D
Then you would use querystring.parse()
, extract the data
parameter from it, then run JSON.parse()
on that value.
然后您将使用querystring.parse()
,从中提取data
参数,然后JSON.parse()
在该值上运行。