如何在JS Rails响应中包含HTML? [英] How do I include HTML in a JS Rails response?

查看:71
本文介绍了如何在JS Rails响应中包含HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个响应HTML和JS(AJAX)查询的FooController:

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

支持它的模板:

# app/views/layouts/foo.html.erb:
<html>...<%= yield %>...</html>

# app/views/layouts/foo.json.erb:
<%= yield %>

还有一个我想在其中渲染局部图像的AJAX模板:

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')) %>";

如果JS模板中仅包含普通的旧JS(例如 alert( 'hi'); ),它使用了我的JS模板。但是,当我放入render(:partial)时,它将使整个响应都使用HTML模板,这意味着它不再是有效的JS。

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?

推荐答案

最新的 Railscast涵盖了这个主题(使用jQuery)

我不太清楚您可能在哪里出了问题,但这是Railscast的一个片段,可以很好地呈现部分片段:

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();

您要将JavaScript存储在哪里?您是否有要保留的Application.js?如果是这样,您是否在javascript_include_tag中的应用程序之前包含 dojo?

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?

这篇关于如何在JS Rails响应中包含HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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