JS模板呈现但在Rails 3.0.7中没有任何反应

时间:2011-06-24 20:55:40

标签: javascript jquery ruby-on-rails erb

show.html.erb:

...
<%= link_to "Start Retrieval", {:action => "retrieve"}, :remote => true %>
<div id="notices">
       <%= render :partial => 'notice' %>  
</div>
....

_notice.html.erb:

<div>Notice</div>

retrieve.js.erb:

#alert('test') //=> does not work
$('#notices').append("<% escape_javascript render :partial => 'notice' %>");

控制器:

def retrieve
    respond_to do |f|
       #f.js {render :js => "alert(typeof jQuery != 'undefined')"} #=> true
       f.js {render :js => "retrieve"} #=> nothing happens
    end
end

输出:

Started GET "/model/1/retrieve" for 127.0.0.1 at 2011-06-24 21:09:44 +0100
  Processing by ModelController#retrieve as JS
  Parameters: {"id"=>"1"}
Completed 200 OK in 50ms (Views: 49.2ms | ActiveRecord: 0.0ms)

正如您所看到的,检索动词不直接涉及模型,而且我没有将@model var传递给模板。我的印象是这只是速记,不应该影响事情。我错了吗?

1 个答案:

答案 0 :(得分:1)

你应该能够做到:

respond_to do |f|
  f.js {}
end

这将呈现与动作(retrieve.js.erb)同名的js.erb文件。

你正在做的是将字符串“retrieve”渲染为纯javascript,相当于在js文件中只是“检索”,如下所示:

<javascript>
retrieve
</javascript>