[英]passing array of objects from js to rails
I am trying to pass an array of objects from js to rails 我试图将一个对象数组从js传递给rails
data.test = [{test: 'asdas'}]
$.ajax({
url: 'evaluate.json',
data: data,
success: function(data){
},
dataType : "json"
});
Rails 轨道
def evaluate
logger.info("#{params.test}")
end
Here the logger statement always gives me out put as 这里的记录器语句总是让我输出
{"0"=>{"test"=>"asdas"}}
I am expecting the below log in rails. 我期待以下登录rails。
[{:test=>"asdas"}]
You should use JSON.stringify
in Javascript, which takes either an array or hash as its argument (since these are the only valid JSON constructions). 您应该在Javascript中使用
JSON.stringify
,它将数组或散列作为其参数(因为这些是唯一有效的JSON结构)。 It returns a form which is the Javascript object serialized to JSON. 它返回一个表单,该表单是序列化为JSON的Javascript对象。
On the Ruby side, you'll receive a JSON encoded string, so you'll need to require 'json'
(this is done automatically in Rails) and use JSON.parse(string)
. 在Ruby方面,你将收到一个JSON编码的字符串,因此你
require 'json'
(这在Rails中自动完成)并使用JSON.parse(string)
。 This will give you a Ruby object. 这将为您提供一个Ruby对象。
Try this: 试试这个:
data.test = [{test: 'asdas'}]
$.ajax({
url: 'evaluate.json',
data: JSON.stringify(data), // Explicit JSON serialization
contentType: 'application/json', // Overwrite the default content type: application/x-www-form-urlencoded
success: function(data){
},
dataType : "json"
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.