[英]Error while parse a json object as ruby object
My question is the next: 我的问题是下一个:
When i try parse a json params with 'json'
gem on RUBY ON RAILS 3 throw this error: 当我尝试用RUBY ON RAILS 3上的'json'
宝石解析json params时抛出此错误:
Unexpected token at
Example 例
I have this object in ruby: 我在ruby中有这个对象:
Then I have this html code: 然后我有这个HTML代码:
<script>
$("#selected").live('click', function(){
jQuery.ajax({url: '<%= deselect_all_checkboxes_path %>', data: {contacts: '<%= contacts.to_json %>'}});
});
</script>
<input type="checkbox" id="selected" value="1" >
I try this code in Rails Console 我在Rails控制台中尝试此代码
JSON.parse(json_string.gsub(/"/, "\""))
Works ok. 工作正常。 However when i try this code: 但是当我尝试这段代码时:
JSON.parse(params[:contacts].gsub(/"/, "\""))
There is a problem in the gsub method. gsub方法存在问题。 In Rails Console works ok but when i am debugging throw the error message. 在Rails控制台工作正常,但在我调试时抛出错误消息。 The problem is with ";" 问题是“;” character. 字符。
Which could be the error? 哪个可能是错误?
You don't want to quote your contacts.to_json
value inside your jQuery, that turns it into a string when you want it to be a JavaScript object literal; 您不希望在jQuery中引用contacts.to_json
值,当您希望它成为JavaScript对象文字时,将其转换为字符串; once your data is a string, it will end up HTML encoded by ERB and you get the mess you're seeing. 一旦你的数据是一个字符串,它将最终由ERB编码的HTML,你得到你看到的混乱。 Try this in your jQuery: 在你的jQuery中试试这个:
data: {contacts: <%= contacts.to_json.html_safe %>}
That should get you a nice JavaScript object literal in your jQuery and that will be serialized into a JSON object (rather than a JSON string) when it is sent back to your server. 这应该会在jQuery中为您提供一个很好的JavaScript对象文字,当它被发送回您的服务器时,它将被序列化为JSON对象(而不是JSON字符串)。
首先对HTML进行Unescape,然后将其解析为直接JSON:
JSON.parse(CGI.unescapeHTML(params[:contacts]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.