[英]Post javascript array to RoR controller using a form hidden field
After browsing many solutions which didn't fit or solve my problem I post this question here: 浏览了许多不适合或无法解决我的问题的解决方案后,我在这里发布了这个问题:
I use javascript to populate hidden fields in a form with data and send it to a rails controller. 我使用JavaScript来用数据填充表单中的隐藏字段,并将其发送到Rails控制器。 This works fine with normal variables but I can't get it to work with arrays.
这可以正常变量正常工作,但我无法使其与数组一起使用。 This is what I do:
这是我的工作:
Javascript (jQuery): Javascript(jQuery):
$("#my_form").submit(function() {
var testvar = 5;
var testarr = [];
testarr[0] = "test data";
testarr[1] = "other data";
$('input[name=testvar]').val(testvar);
$('input[name=testarr]').val(JSON.stringify(testarr));
})
RoR controller: RoR控制器:
def create
testvar = params[:testvar]
data = params[:testarr]
testarr = ActiveSupport::JSON.decode(data)
// other commands
end
It works fine for testvar but for the array it always creates the error 它对于testvar正常工作,但对于数组它总是会产生错误
can't convert nil into String
What am I doing wrong? 我究竟做错了什么?
The request looks like this: 该请求看起来像这样:
{"utf8"=>"✓",
"authenticity_token"=>"1qFA3NTqUxoI1jusbwrVi5AWIpJz9tbUGR0KuCtNKTs=",
"testvar"=>"5",
"testarr"=>"[\"test data\",
\"other data\"]",
"commit"=>"Submit my form data"}
Thanks in advance, your help is highly appreciated! 在此先感谢您的帮助!
If you name your input fields with [] at the end, rails will map it to params as an array 如果以[]结尾命名输入栏,rails会将其映射为数组
<input type="hidden" name="testarr[]" />
$(....).val(testarr.join(","))
Or append a new input for each instead of join, they all have the same input name 或为每个附加新输入而不是加入,它们都具有相同的输入名称
$(....).submit(....
$form = $(this)
testarr.each
$form.append('<input type="hidden" name="testarr[]" value="...itemValue..." />')
In controller 在控制器中
params[:testarr].each do ....
Typed on an ipad, please forgive incomplete code, hopefully it gives you some ideas 在ipad上输入内容,请原谅不完整的代码,希望它能为您提供一些建议
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.