rails使用javascript渲染视图onclick [英] rails render view onclick with javascript

查看:57
本文介绍了rails使用javascript渲染视图onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个视图,用户可以在其中点击不同的按钮,并根据他们点击的按钮呈现不同的内容。我试过用JS完成这个,但是不能真正让它工作。我在我看来做了一个按钮:

I'm trying to create a view, where users can click on different buttons and render different content based on the buttons they click. I've tried getting this done with JS but can't really get it to work. I made a button in my view:

<div class="link">
  <%= link_to "Greetings", "#" %>
</div>
<div id="show"></div>

然后在job.js.erb中:

then in job.js.erb:

$(function() {
  $('.link').click(function() {
    $('#show').append("<%=escape_javascript render(:partial => 'show' %>");
  });
});

遗憾的是资产不支持渲染,但我真的不知道实现这一目标的最佳方法是什么。

unfortunately render is not supported in assets, but I don't really know what the best way is to make this happen.

推荐答案

您可以尝试的一种方法是让按钮单击由AJAX转到控制器操作,然后呈现名称为的文件< action_name> ; .js.erb 。此文件将能够调用 render 操作。

One way you can try is to let the button click go to a controller action, by AJAX, and then render the file with name <action_name>.js.erb. this file will then be able to call the render action.

我将通过以下内容详细说明:

I will expatiate more with the following:

假设有问题的资源是 Greetings 并且您有一个例如, dynamic_show Greetings 控制器中的操作,你有一个 dynamic_show_greetings_path 路由到此行动。

Assuming the resource in question is Greetings and you have a dynamic_show action in the Greetings controller, for example, and you have a dynamic_show_greetings_path routing to this action.

从您的视图中,您可以:

From inside your view, you can have:

<div class="link">
  <%= link_to "Greetings", dynamic_show_greetings_path, remote: true %>
</div>
<div id="show"></div>

Greetings#dynamic_show 操作将是如下:

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

然后,在你的查看目录,你有一个 dynamic_show.js.erb 文件,它将包含附加动态视图的脚本如下:

then, in your view directory, you have a dynamic_show.js.erb file, which will contain the script to append the dynamic view as follow:

$('#show').html("<%=escape_javascript render(:partial => 'show') %>");

这就解决了这个问题!

当然,现在让它变得动态,你必须将params传递给控制器​​,然后根据得到的响应渲染内容。

Of course, to now make it dynamic, you have to then pass in params to the controller, and then render content based on the response gotten.

PS:


  • 在链接上设置 remote:true 可确保呼叫为 AJAX 调用。

  • 默认情况下,控制器操作呈现的文件名与操作名称相同,因此, dynamic_show 回复 js 将呈现 dynamic_show.js.erb

  • setting remote: true on the link ensures that the call will be an AJAX call.
  • controller actions by default renders the file with same name as the action name, therefore, dynamic_show responding to js will render dynamic_show.js.erb

希望这能为你带来一丝光明......;)

Hope this throws a great light into it for you... ;)

这篇关于rails使用javascript渲染视图onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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