Rails 3 不加载 .js.erb 文件

发布于 2024-11-30 16:41:29 字数 313 浏览 1 评论 0原文

我希望加载并执行两个名为“create”和“update”的 .js.erb 文件,以在提交表单后用更新的部分替换我的视图之一中的表。

这些文件都包含以下内容(它们是相同的)

$('table#rating').replaceWith("<%= escape_javascript(render :partial => 'home/rating') %>");

但是我不确定将 .js.erb 文件放在哪里(与我的 html.erb 页面在同一视图中?)以及如何在表单提交时加载/触发它们。任何帮助将不胜感激。

I would like two .js.erb files, named "create" and "update" to load and be executed to replace a table in one of my views with an updated partial after a form is submitted.

The files both contain the following (they are identical)

$('table#rating').replaceWith("<%= escape_javascript(render :partial => 'home/rating') %>");

However I am unsure where to put the .js.erb files (in the same view as my html.erb page?) and how to load/trigger them when the form submits. Any help would be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

负佳期 2024-12-07 16:41:29

是的,您将 .js.erb 文件放置在与您使用它们的 .html.erb 文件相同的位置。为了让 Rails 使用它们,您需要告诉 Rails 表单应该异步提交(通过 AJAX)。为此,只需添加 :remote =>; true 到您的表单标记。例如

<%= form_for @some_model, :remote => true do %>
<!-- form stuff... -->
<% end %>

Yes, you place .js.erb files in the same location as the .html.erb files you're using them with. In order for Rails to use them, you need to tell Rails that the form should be submitted asynchronously (via AJAX). To do this, just add a :remote => true to your form tag. For instance

<%= form_for @some_model, :remote => true do %>
<!-- form stuff... -->
<% end %>
像你 2024-12-07 16:41:29

为了使用 Ajax 提交表单,您需要指定 :remote =>亚历克斯指出的 true 选项。

在处理表单提交的控制器中还应该能够响应 Ajax 请求。它应该有类似以下内容。

class FormHandlingController < ApplicationController

  def create
    ...
    respond_to do |format|
      format.js
    end
  end

end

您应该将 craete.js.erb 放置在 app/views/form_handling_controllers/ 目录下。

In order to submit a form with Ajax, you need to specify :remote => true option as pointed out by Alex.

In the controller that handles the form submission should also be able to respond to Ajax request. It should have something like following.

class FormHandlingController < ApplicationController

  def create
    ...
    respond_to do |format|
      format.js
    end
  end

end

You should place your craete.js.erb under app/views/form_handling_controllers/ directory.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文