简体   繁体   English

RJ中的UJS部分渲染3

[英]UJS partial rendering in Rails 3

I'm struggling to get my head around how to implement UJS in Rails (specifically, Rails 3 with jQuery). 我正在努力探讨如何在Rails中实现UJS(特别是使用jQuery的Rails 3)。 I've worked through Ryan's Railscast , and can follow what to do when submitting a form via AJAX, but I'm having trouble extending this concept to attaching a javascript function to a html element in my view files. 我已经通过Ryan的Railscast工作了 ,并且可以按照通过AJAX提交表单时要做的事情,但是我无法将这个概念扩展到将javascript函数附加到我的视图文件中的html元素。 Ultimately, I would like to be able to create a form where a different partial is rendered depending upon which radio button from a series is selected. 最后,我希望能够创建一个表单,根据选择的系列中的哪个单选按钮呈现不同的部分。 Should I be looking at using the Prototype legacy helpers for this? 我应该考虑使用Prototype遗留助手吗? And when do I need to create a .js.erb file? 我什么时候需要创建.js.erb文件?

Sorry for the newbie question, I've been unable to find much that explicitly outlines the concept of UJS and how to use it in a Rails app/switch over code from a RJS approach. 很抱歉新手问题,我一直无法找到明确概述UJS的概念以及如何在Rails应用程序中使用它/切换来自RJS方法的代码。 Any help would be much appreciated! 任何帮助将非常感激!

By using the remote => true on the form, your data will go to the server and all javascript returned will simply be executed in the context of the page, so here is a simple example: 通过在表单上使用remote => true ,您的数据将转到服务器,并且返回的所有javascript将仅在页面的上下文中执行,因此这是一个简单的示例:

<%= form_tag '/action_path', :remote => true do %>
  <%= radio_button_tag 'partial', 'one' %>
  <%= radio_button_tag 'partial', 'two' %>
  <%= submit_tag 'select' %>
<% end %>

<div id="partial_holder">

</div>

On the server 在服务器上

def action
  #do whatever you want with parameters
end

On the action.js.erb file 在action.js.erb文件中

$('#partial_holder').html("<%= escape_javascript(render(:partial => params[:partial])) %>")

On the action.js.erb file 在action.js.erb文件中

$('#partial_holder').html(<%= escape_javascript(render(:partial => params[:partial])) %>)

The above line has a minor mistake, the ruby tags inside html method should be inside quotes. 上面的行有一个小错误,html方法里面的ruby标签应该在引号内。 The following will work. 以下将有效。

$('#partial_holder').html("<%= escape_javascript(render(:partial => params[:partial])) %>")

For some strange reasons for me the abovementioned solution did not work. 由于我的一些奇怪的原因,上述解决方案不起作用。 This did: 这样做:

Element.replace('element_id', '<%= escape_javascript(render(:partial=>"foo")) %>');

Note the ' that surrounds the ruby block. 请注意围绕红宝石块的'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM