Submit form using link_to in rails

Deadly 提交于 2019-11-29 18:11:49

问题


I'm trying to submit a form using link_to as follows:

 <%= 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?


回答1:


You can use:

<%= link_to 'submit', "#", :onclick => "$('#form_id').submit()" %>

if you are using JQuery and a later version of 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()" %>



回答2:


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...

...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.

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:

$(document).on('click', '[data-submit-form]', function(e) {
  e.preventDefault();
  $(this).closest('form').submit()
}


来源:https://stackoverflow.com/questions/11645153/submit-form-using-link-to-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!