如何从Rails应用程序创建可嵌入的HTML表单 [英] How to create embeddable HTML form from a Rails application
问题描述
我想创建一个可嵌入的HTML < form>
,将POST发送到rails控制器。该表单将嵌入到非Rails网站上。
你有什么方法来创建这样的表单?我应该使用< iframe>
还是JS?或者完全不同的东西?
作为这个问题的次要部分,我还需要这种形式来将事件冒泡到它的父页面中嵌入到,这样我就可以捕获表单的所有字段,以调用外部API,如Google Events或Marketo。 解决方案
您可以包含正常的HTML 表单
,该表单的动作设置为您需要的路线。
表单将创建一个名称为雇员:
< form action =http://example.com/employees? return_url = ... some_url ...
method ='post'>
< input name =employee [name]type = text />
< input type = submit value ='create'/>
< / form>
请确保在您的控制器中重定向回您的non rails站点。当你的动作也被用在rails网站本身时,你需要一些方法来表明你的动作应该重定向到哪里。
def create
employee = Employee.create(params [:employee])
if params [:return_url]
redirect_to params [:return_url]
else
redirect_to employee_path (员工)
结束
结束
请务必关闭 forgery_protection 。
class EmployeesController< ApplicationController
skip_before_filter:verify_authenticity_token,:only => [:create]
#actions
end
I want to create an embeddable HTML <form>
that POSTs to a rails controller. This form would be embedded on a non-rails site.
What approach have you taken to create a form like this? Should I use an <iframe>
, or JS? Or something completely different?
As a secondary part to this question, I'd also need this form to be able to "bubble up" events into the parent page that it is embedded into, such that I could capture all of the fields of the form to make calls to external APIs like Google Events or Marketo.
You can just include normal HTML form
which has its action set to the route you need.
This form will create an employee with the given name:
<form action="http://example.com/employees?return_url=...some_url..."
method='post'>
<input name="employee[name]" type=text/>
<input type=submit value='create'/>
</form>
Be sure, in your controller to redirect back to your non rails site. When your action is also used in the rails site itself, you'll need some way to indicate where your action should redirect to.
def create
employee = Employee.create(params[:employee])
if params[:return_url]
redirect_to params[:return_url]
else
redirect_to employee_path(employee)
end
end
Be also sure to disable forgery_protection for that action.
class EmployeesController < ApplicationController
skip_before_filter :verify_authenticity_token, :only => [:create]
# actions
end
这篇关于如何从Rails应用程序创建可嵌入的HTML表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!