【发布时间】:2012-02-27 21:56:26
【问题描述】:
我想嵌入一个 JSON 对象作为表单参数发送到 rails 服务器。
这是我目前所拥有的:
<% form_tag :action => :create, :controller => :objects do %>
<%= text_field_tag :object %>
<%= submit_tag %>
<% end %>
和用于填充该字段的 javascript。 data 是有效的 JSON。
<script type="text/javascript">
$j(function(){
jQuery("#proposal").val(JSON.stringify(data));
});
</script>
但是,当服务器收到 POST 时,我需要将 params[:object] 转换为哈希,但它被双重转义,即使使用 .gsub("\\", ""),JSON.parse 似乎也有问题,实际上并没有转换为 JSON字符串中的对象。
这是服务器收到的我的 JSON 字符串:
"{\"name\":\"hello there,
I am JSON!\",
\"template_id\":1,
\"variables\":{\"hello\":\"there\",
\"me\":\"you\"},
\"sections\":\"[{\\\"name\\\": \\\"Template Section\\\",
\\\"contents\\\": [{\\\"id\\\": 1,
\\\"name\\\": \\\"RENAMED!\\\"}]},
{\\\"name\\\": \\\"section2\\\",
\\\"contents\\\": [{\\\"name\\\": \\\"something\\\",
\\\"body\\\": \\\"nothing\\\"},
{\\\"id\\\": 2,
\\\"name\\\": \\\"I renamed you\\\",
\\\"variables\\\": {\\\"hello\\\": \\\"i'm amazing\\\"}}]}]\",
\"attachments\":\"[{\\\"media_id\\\": 1}]\"}"
【问题讨论】:
标签: javascript jquery ruby-on-rails ruby json