javascript - 通过帖子传递对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4255848/
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
javascript - pass object via post
提问by Hailwood
I have an object that looks like this
我有一个看起来像这样的对象
var obj = { p1 : true, p2 : true, p3 : false }
var obj = { p1: true, p2: true, p3: false }
I am looking to try and pass this object as part of a post request.
我希望尝试将此对象作为发布请求的一部分传递。
however on the other end (in php) all I get is
然而在另一端(在 php 中)我得到的是
[object Object]
[对象对象]
How can I send an object via post?
如何通过邮寄发送对象?
basically what I am trying to do is
基本上我想做的是
I have an input that is hidden and is created like so
我有一个隐藏的输入并且是这样创建的
<input id="obj" type="hidden" name="obj[]">
<input id="obj" type="hidden" name="obj[]">
which is part of a hidden form.
这是隐藏表格的一部分。
when a button is pressed I have
当按下按钮时,我有
$(#obj).val(obj);
$('form').submit();
请不要建议使用ajax,因为我必须以这种方式下载动态创建的文件。
回答by Matt
You need to serialize/convert the object to a string before submitting it. You can use jQuery.param()
for this.
在提交之前,您需要将对象序列化/转换为字符串。您可以jQuery.param()
为此使用。
$('#obj').val(jQuery.param(obj));
回答by T.J. Crowder
You might consider using JSONnotation to send the object to the server. If you include a JSON parser/rendererin your page,(it's built in on all modern browsers now, and also IE8 in standards mode)you can convert the object into a string preserving its full object graph. Most server-side languages now have JSON parsing available for them (in PHP it's json_decode
, for instance). You can put that string in your hidden form field before sending the form.
您可能会考虑使用JSON表示法将对象发送到服务器。如果您在页面中包含JSON 解析器/渲染器(它现在内置在所有现代浏览器中,并且在标准模式下也内置在 IE8 中),您可以将对象转换为保留其完整对象图的字符串。大多数服务器端语言现在都有可用的 JSON 解析(例如在 PHP 中json_decode
)。您可以在发送表单之前将该字符串放入隐藏的表单字段中。
That would look like this:
看起来像这样:
$('#obj').val(JSON.stringify(obj));
$('form').submit();
...and your server-side would see a string in the form
...并且您的服务器端会在表单中看到一个字符串
{ "p1" : true, "p2" : true, "p3" : false }