如何在不渲染新页面的情况下在 Rails 中的页面内执行操作 [英] How to perform an action within a page in Rails without rendering a new page

查看:45
本文介绍了如何在不渲染新页面的情况下在 Rails 中的页面内执行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 rails 应用程序中,我尝试添加一个联系人用户弹出框,用于向用户发送电子邮件.

In my rails app I'm trying to add a contact user popup box which delivers an email message to a user.

我有 javascript 来显示弹出窗体,它本身是一个部分.

I have the javascript in place to display the popup form, which is itself a partial.

当用户点击联系表单上的提交时,它会调用一个控制器操作来发送邮件.提交消息后,我想留在同一页面上,但隐藏弹出框.我的问题是我无法获得传递邮件的控制器操作而不是呈现自己的视图.我试过

When the user clicks submit on the contact form it calls a controller action which delivers the mail. After submitting the message I want to stay on the same page, but hide the popup box. My problem is that I can't get the controller action which delivers the mail not to render its own view. I tried

render nothing: true

但这只会呈现一个空白页面.

But that simply renders a blank page.

我的表单设置如下

= form_tag({:controller => 'users', :action => 'contact_user'}, :method => 'put') do 

在我的路由配置中我有

resources :users
  collection do
     put 'contact_user'
  end

推荐答案

如果您通过 AJAX 提交表单,您可以做您想做的事.

If you submit your form via AJAX, you can do what you're trying to do.

添加 :remote =>true 到您的表单将完成此操作:

Adding :remote => true to your form will accomplish this:

= form_tag({:controller => 'users', :action => 'contact_user'}, :method => 'put', :remote => true) do 

现在,表单提交将作为 AJAX 请求命中您的控制器.然后,您应该能够按照您的建议不渲染任何内容,甚至可以执行诸如渲染 .js.erb 之类的操作来执行一些 Javascript(例如,隐藏您正在谈论的弹出窗口).

Now, the form submission will hit your controller as an AJAX request. You should then be able to either render nothing, as you suggested, or even do something like render a .js.erb to execute some Javascript instead (say, to hide the popup you're talking about).

这篇关于如何在不渲染新页面的情况下在 Rails 中的页面内执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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