[英]How do I include HTML in a JS Rails response?
I have a FooController that responds to HTML and JS (AJAX) queries: 我有一个响应HTML和JS(AJAX)查询的FooController:
# app/controllers/foo_controller.rb:
class FooController < ApplicationController
layout 'foo'
def bar
respond_to do |format|
format.html # foo/bar.html.erb
format.js # foo/bar.js.erb
end
end
end
The templates to support it: 支持它的模板:
# app/views/layouts/foo.html.erb:
<html>...<%= yield %>...</html>
# app/views/layouts/foo.json.erb:
<%= yield %>
And an AJAX template in which I want to render a partial: 还有一个我要渲染部分的AJAX模板:
# app/views/foo/bar.js.erb:
dojo.byID('some_div').innerHTML = "<%= escape_javascript(render(:partial => 'some/partial')) %>";
If the JS template just has plain old JS in it (like alert('hi');
), it uses my JS template. 如果JS模板中只有普通的旧JS(比如
alert('hi');
),它就会使用我的JS模板。 When I put in the render(:partial), though, it makes the whole response use the HTML template, which means it's no longer valid JS. 但是,当我放入render(:partial)时,它会使整个响应使用HTML模板,这意味着它不再是有效的JS。
A possible solution is to use a function for the layout: 一种可能的解决方案是使用布局函数:
class FooController < ApplicationController
layout :choose_layout
...
private
def choose_layout
return nil if request.xhr?
'foo'
end
end
But my version should work! 但我的版本应该工作! Why doesn't it?
为什么不呢?
The most recent Railscast covers this topic (using jQuery) . 最新的Railscast涵盖了这个主题(使用jQuery) 。
I'm not quite seeing where you might be going wrong, but here's a snippit from the Railscast that works just fine to render a partial: 我不太明白你可能会出错的地方,但是这里有一个来自Railscast的snippit可以正常工作以呈现部分:
// views/reviews/create.js.erb
$("#new_review").before('<div id="flash_notice"><%= escape_javascript(flash.delete(:notice)) %></div>');
$("#reviews_count").html("<%= pluralize(@review.product.reviews.count, 'Review') %>");
$("#reviews").append("<%= escape_javascript(render(:partial => @review)) %>");
$("#new_review")[0].reset();
Where are you storing your Javascript? 你在哪里存储你的Javascript? Do you have an Application.js that you're keeping things in?
你有一个Application.js,你有什么东西? If so, are you including "dojo" before "application" in your javascript_include_tag?
如果是这样,你在javascript_include_tag中的“应用程序”之前是否包含“dojo”?
Try the following; 尝试以下方法;
class FooController < ApplicationController
layout 'foo'
def bar
respond_to do |format|
format.html
format.js { render :layout => false }
end
end
end
Hope that helps. 希望有所帮助。
JK JK
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.