将对象数组从js传递到rails [英] passing array of objects from js to rails
问题描述
我正在尝试将对象数组从js传递到rails
I am trying to pass an array of objects from js to rails
data.test = [{test: 'asdas'}]
$.ajax({
url: 'evaluate.json',
data: data,
success: function(data){
},
dataType : "json"
});
铁路
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.
[{:test=>"asdas"}]
推荐答案
您应该在Javascript中使用JSON.stringify
,它使用数组或哈希作为参数(因为这是唯一有效的JSON构造).它返回一个表单,该表单是序列化为JSON的Javascript对象.
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). It returns a form which is the Javascript object serialized to JSON.
在Ruby端,您将收到一个JSON编码的字符串,因此您需要require 'json'
(在Rails中自动完成)并使用JSON.parse(string)
.这将为您提供一个Ruby对象.
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)
. This will give you a Ruby object.
这篇关于将对象数组从js传递到rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!