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
Rails
def evaluate
logger.info("#{params.test}")
end
Here the logger statement always gives me out put as
这里logger语句总是输出as
{"0"=>{"test"=>"asdas"}}
I am expecting the below log in rails.
我期待着下面的日志记录在rails中。
[{:test=>"asdas"}]
2 个解决方案
#1
4
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.
您应该使用JSON。Javascript中的stringify,它以数组或散列作为参数(因为这些是唯一有效的JSON结构)。它返回一个将Javascript对象序列化为JSON的表单。
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.
在Ruby端,您将收到一个JSON编码的字符串,因此需要使用' JSON '(这在Rails中是自动完成的)并使用JSON.parse(string)。这将为您提供一个Ruby对象。
#2
2
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"
});
#1
4
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.
您应该使用JSON。Javascript中的stringify,它以数组或散列作为参数(因为这些是唯一有效的JSON结构)。它返回一个将Javascript对象序列化为JSON的表单。
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.
在Ruby端,您将收到一个JSON编码的字符串,因此需要使用' JSON '(这在Rails中是自动完成的)并使用JSON.parse(string)。这将为您提供一个Ruby对象。
#2
2
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"
});