Using Rails link_to for links that post

后端 未结 5 1049

I have a link that I need to submit a post request with. Normally, I\'d use jQuery and prevent the link\'s default behavior and then submit a form to the destination. This s

5条回答
  •  一向
    一向 (楼主)
    2020-12-02 14:45

    In order to POST data, you need a form. However, you don't need a submit button. If you want this to look like a link for some reason, you can actually make it a link that submits the form via JavaScript. In the example below, the POST resource is just a REST action that does not require any fields so there are no form input controls. If you wanted to post some data, just put hidden input fields in the form.

    <%= form_tag('http://something_postable', :method => :post, :class => 'internal') %>
    <%= link_to_function('Label for Link', 'previous("form").submit()', :title => 'Hover text for link') %>
    

    The form is assigned a class so you can style it or hide it via CSS (e.g. 'display: inline')

提交回复
热议问题