Ruby-on-rails 在 rails 中使用 link_to 提交表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11645153/
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
Submit form using link_to in rails
提问by random
I'm trying to submit a form using link_to as follows:
我正在尝试使用 link_to 提交表单,如下所示:
<%= form_for(@post, :url=> '/post/action', :method=> 'post', :html => {:id=>'form_id'} ) do |f| %>
....
<%= link_to 'submit', "/post/action", :onclick=>"document.getElementById('form_id').submit()" %>
....
but it is not posting the form, it is simply redirecting my form to the specified url. Does anyone know how to do this?
但它没有发布表单,它只是将我的表单重定向到指定的 url。有谁知道如何做到这一点?
回答by Paulo Fidalgo
You can use:
您可以使用:
<%= link_to 'submit', "#", :onclick => "$('#form_id').submit()" %>
if you are using JQuery and a later version of rails.
如果您使用的是 JQuery 和更高版本的 rails。
Above will work but if you have a really long page it will navigate to top of the page because of "#" so if you want to avoid that you can do:
上面可以工作,但如果你有一个很长的页面,它会因为“#”而导航到页面顶部,所以如果你想避免这种情况,你可以这样做:
<%= link_to 'submit', "", :onclick => "$('#form_id').submit()" %>
回答by Stefan Kanev
I think both things happen. The browser starts to submit the form, but it also follows the link's href. You can fix it by linking to #instead of /post/action...
我认为这两件事都会发生。浏览器开始提交表单,但它也遵循链接的href. 您可以通过链接到#而不是/post/action...来修复它
...however, I don't recommend doing it. There are a few better approaches:
......但是,我不建议这样做。有几个更好的方法:
First, you can use a button instead of a link. You'll have to style it to make it look like a link, but that should not be a problem. It will be better, because it won't break the Principle of Least Surprise (people who read the code expect forms to be submitted with buttons) and you won't need the JavaScript.
首先,您可以使用按钮而不是链接。您必须对其进行样式设置以使其看起来像一个链接,但这应该不是问题。它会更好,因为它不会破坏最小惊喜原则(阅读代码的人希望表单提交带有按钮)并且您不需要 JavaScript。
If you insist on using a link, you should at least move the JavaScript code from the view to a JavaScript file. Then have this behavior added unobtrusively (although, you won't have a good fallback with the link). Assuming you're using jQuery, it should be as simple as:
如果您坚持使用链接,您至少应该将 JavaScript 代码从视图移动到 JavaScript 文件。然后不显眼地添加此行为(虽然,您不会对链接有很好的回退)。假设您使用的是 jQuery,它应该很简单:
$(document).on('click', '[data-submit-form]', function(e) {
e.preventDefault();
$(this).closest('form').submit()
}

