将 Rails link_to 用于发布的链接 [英] Using Rails link_to for links that post

查看:24
本文介绍了将 Rails link_to 用于发布的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个链接,我需要用它来提交发布请求.通常,我会使用 jQuery 并阻止链接的默认行为,然后向目标提交表单.这似乎是 Rails 应该能够帮助我解决的问题.果然,link_to 方法有一个用于指定 POST http 方法的选项:

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 seems like something Rails should be able to help me out with. Sure enough, the link_to method has an option for specifying a POST http method:

link_to "Profile", 'http://example.com/profile', method: :post

这可行,但我也需要添加 2 个参数.我试过了:

That works, but I need to add 2 parameters too. I tried:

link_to "Profile", 'http://example.com/profile', method: post, param1: 'value1', param2: 'value2'

那只是将这些参数添加到 <a> HTML 元素中,但在单击链接时没有提交这些参数:

That just added those parameters to the <a> HTML element, but didn't submit those when clicking the link:

<a rel="nofollow" param1="value1" param2="value2" data-method="post" href="http://example.com/profile">Profile</a>

有没有办法使用 link_to 或任何其他 Rails 方法使用参数执行 POST 请求?我使用的是 Rails 3.2.9.

Is there a way to do a POST request with parameters using link_to or any other Rails method? I'm using Rails 3.2.9.

推荐答案

简短的回答是,如果您所说的参数"是表单字段,那么您根本无法做到这一点(至少不是以直接的方式)我可以看到).您应该改为使用带有提交按钮的表单,其样式看起来像一个链接(如果这是您想要的样子).

The short answer is that if what you mean by "parameters" is form fields, then you simply can't do this (at least not in a straightforward way that I can see). You should instead use a form with a submit button, styled to look like a link (if that's what you want it to look like).

另一方面,如果您的意思是查询参数,那么这将起作用:

If on the other hand you had meant query parameters, then this would work:

link_to "Profile", profile_path(@profile.id, param1: 'value1', param2: 'value2'), method: :post

这篇关于将 Rails link_to 用于发布的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆