在js呈现部分。erb文件

时间:2022-11-07 08:42:34

I'm trying to create an ajax-based comment form which will update my comments list when submitted. Pretty basic stuff.

我正在尝试创建一个基于ajax的评论表单,它将在提交时更新我的评论列表。非常基本的东西。

I have a partial comments/_single.html.haml which has a single <li> tag with basic comment info and here is my comments/create.js.erb file (actually these are three different test files merged into one to show you what my problem is):

我有部分注释/_single.html。haml有一个带有基本评论信息的

  • 标签,这是我的评论/创建。js。erb文件(实际上这是三个不同的测试文件合并到一个中,向您展示我的问题是什么):

  • 标签,这是我的评论/创建.js.erb文件(实际上这是三个不同的测试文件合并到一个中,向您展示我的问题是什么):
  • $('#comments ul.comments').append("<%= render :partial => 'comments/single', :locals => { :c => @comment } %>");
    $('#comments ul.comments').append("<%= render :partial => 'comments/foobar' %>");
    $('#comments ul.comments').append("foobar");
    alert('foobar');
    

    The content for comments/_foobar.html.haml is just foobar, no html inside. My problem is that first two lines doesn't work. There are no errors in my dev server console, object inspector says that comment code was returned correctly but they are not added to my comments list. The third line works fine and so the fourth one. It looks like there are some problems with using render.

    评论的内容/ _foobar.html。haml只是foobar,里面没有html。我的问题是前两行不行。在我的dev服务器控制台中没有错误,object inspector说注释代码被正确地返回,但是它们没有被添加到我的注释列表中。第三行写得很好,第四行写得很好。看起来使用渲染有一些问题。

    1 个解决方案

    #1


    93  

    When rendering partials inside Javascript code, you should use the escape_javascript method, like so

    当在Javascript代码中呈现部分时,应该使用escape_javascript方法,比如这样

    $('#comments ul.comments').append("<%= escape_javascript render(:partial => 'comments/single', :locals => { :c => @comment }) %>");
    

    This method is aliased as j, so you can also do this

    这个方法别名为j,所以您也可以这样做

    $('#comments ul.comments').append("<%= j render(:partial => 'comments/foobar') %>");
    

    The method Escapes carriage returns and single and double quotes for JavaScript segments ActionView::Helpers::JavaScriptHelper Rails docs

    方法转义返回和JavaScript段ActionView:: helper::JavaScript Rails文档的单引号和双引号

    #1


    93  

    When rendering partials inside Javascript code, you should use the escape_javascript method, like so

    当在Javascript代码中呈现部分时,应该使用escape_javascript方法,比如这样

    $('#comments ul.comments').append("<%= escape_javascript render(:partial => 'comments/single', :locals => { :c => @comment }) %>");
    

    This method is aliased as j, so you can also do this

    这个方法别名为j,所以您也可以这样做

    $('#comments ul.comments').append("<%= j render(:partial => 'comments/foobar') %>");
    

    The method Escapes carriage returns and single and double quotes for JavaScript segments ActionView::Helpers::JavaScriptHelper Rails docs

    方法转义返回和JavaScript段ActionView:: helper::JavaScript Rails文档的单引号和双引号