Ruby-on-rails rails 提交不带刷新的表单,:remote => true
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16242124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rails submit form w/o refresh, :remote => true
提问by vivianh
I'm trying to submit a form in rails without refreshing the page afterwards. I've been looking around online, but it seems that adding :remote => true doesn't seem to change my form the way I thought it would. Right now I have each question having a number of answers, and each one is connected to a radio button, but I've hidden the radio button so clicking on the label itself submits the form. Does the page refresh as a result of the radio button form submission? I'm really not sure, and would appreciate any help at this point...
我正在尝试在 Rails 中提交表单,之后不刷新页面。我一直在网上环顾四周,但似乎添加 :remote => true 似乎并没有像我想象的那样改变我的形式。现在我的每个问题都有许多答案,每个问题都连接到一个单选按钮,但我隐藏了单选按钮,因此单击标签本身会提交表单。页面是否因单选按钮表单提交而刷新?我真的不确定,在这一点上会很感激任何帮助......
<%= form_for(uanswer, :remote => true) do |f| %>
<% answers.each_with_index do |answer, i| %>
<% unless answered_flag %>
<%= f.radio_button :answer_id, answer.id, :class => "radio hide",
:onclick => "this.form.submit();" %>
<% end %>
<%= f.label :answer_id, answer.answer, :class => "answer",
:value => answer.id %>
<% end %>
The generated HTML form looks more or less like this:
生成的 HTML 表单或多或少是这样的:
<form accept-charset="UTF-8" action="/uanswers" class="new_uanswer"
data-remote="true" id="new_uanswer" method="post"><div
style="margin:0;padding:0;display:inline"><input
name="utf8" type="hidden" value="?"><input name="authenticity_token"
type="hidden" value="PY5ACVmrvDnt/iYF8RK6O7tDKAn2G2dFdLeBNZw5MJ4="></div>
</form>
回答by Brian Chapman
The remote=>true isn't doing anything for you right now as you are bypassing rails with the this.form.submit(). You need to submit the form asynchronously. See Submit form in rails 3 in an ajax way (with jQuery)for a solution to a similar question.
当您使用 this.form.submit() 绕过 rails 时,remote=>true 现在没有为您做任何事情。您需要异步提交表单。有关类似问题的解决方案,请参阅以 ajax 方式(使用 jQuery)提交 rails 3 中的表单。
回答by Jose Castellanos
Changing this.form.submit()to $(this).closest('form').submit()worked for me. I use the "onchange" method instead on "onclick" for my form fields though.
更改this.form.submit()到$(this).closest('form').submit()对我来说有效。不过,我在表单字段中使用“onchange”方法而不是“onclick”。

