将对象数组从 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"}}
我期待以下登录 rails.
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(字符串)
.这会给你一个 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屋!