How do I include HTML in a JS Rails response?

十年热恋 提交于 2019-12-31 14:53:34

问题


I have a FooController that responds to HTML and JS (AJAX) queries:

# 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:

# 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. 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.

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?


回答1:


The most recent Railscast covers this topic (using 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:

// 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? Do you have an Application.js that you're keeping things in? If so, are you including "dojo" before "application" in your javascript_include_tag?




回答2:


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.

J.K.



来源:https://stackoverflow.com/questions/300498/how-do-i-include-html-in-a-js-rails-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!