Rails ajax 调用不将 erb 元素转换为 html

Rails ajax call not converting erb elements to html

可能有一个更好的标题,但我不知道技术术语是什么

无论如何,我正在执行 ajax 调用,将 link 附加到 div。 link 包含 erb 代码,例如

#{post.comments.count}

$('#comments_<%= @post.id %>').append("<%= escape_javascript (link_to 'view all #{post.comments.count} comments', post_comments_path(@post), remote: true, class: 'more-comments', id: 'more_comments_#{post.id}', data: {post_id: @post.id, type: 'html', value: '#{post.comments.count}' }) %>"); }`

link 最终看起来像这样:

<br/><br>
view all #{post.comments.count} comments
<br>
<br>

这是 link 检查时的样子:

<a class="more-comments" id="more_comments_#{post.id}" data-post-id="4" data-type="html" data-value="#{post.comments.count}" data-remote="true" href="/posts/4/comments">view all #{post.comments.count} comments</a>

当我尝试在代码中使用 <%= %> 时,我最终遇到了 500 个错误。与其他 AJAX link 一起使用 <%= %> 我不会被抛出这 500 个错误。

例如:

这个有效:

$('#more_comments_<%= @post.id %>').html("view all <%= @post.comments.count %> comments");

这不是:

$('#comments_<%= @post.id %>').append("<%= escape_javascript (link_to 'view all <%= @post.comments.count %> comments', post_comments_path(@post), remote: true, class: 'more-comments', id: 'more_comments_<%= @post.id %>', data: {post_id: @post.id, type: 'html', value: <%= @post.comments.count %> }) %>");

这将引发此错误:

POST http://localhost:3000/posts/4/comments 500 (Internal Server Error)

我尝试通过 'splicing' 和 link 以及 JS 持有的变量来规避此问题:

$('#comments_' + Append.id).append("<%= link_to 'view all " + Append.comment_count + " comments', post_comments_path(" + Append.id + "), remote: true, class: 'more-comments', id: 'more_comments_" + Append.id + "', data: {post_id: " + Append.id + ", type: 'html', value: " + Append.comment_count + " } %>");

而且我仍然收到 500 错误。

评论控制器看起来像这样,

def index
        @post = Post.find(params[:post_id])
        @comments = @post.comments.all.order("created_at ASC")
        respond_to do |format|
            format.html { render layout: !request.xhr? }
            format.js
        end 
    end
end

我在 Whosebug 上找不到这个确切的问题,我可能只是没有用谷歌搜索(TIL 谷歌搜索是一个词)正确的关键词。 很多 E-love 对于那些做到这一点的人来说

您似乎在尝试使用 ERB 标签 (<%= %>),而您应该使用标准 Ruby 字符串插值 (#{ })。

ERB 标签只能在某些地方使用,即 .erb 个文件。

此外,ERB标签不能嵌套。所以在你的例子中,

$('#comments_<%= @post.id %>').append("<%= escape_javascript (link_to 'view all <%= @post.comments.count %> comments', post_comments_path(@post), remote: true, class: 'more-comments', id: 'more_comments_<%= @post.id %>', data: {post_id: @post.id, type: 'html', value: <%= @post.comments.count %> }) %>");

问题是 escape_javascript 方法中的 ERB 标签,应该用标准 Ruby 字符串插值替换。

仅供参考,除非您显示实际错误,否则说您有 500 错误是没有用的。由于 500 是 'generic' 错误,它可能由几乎无限的情况引起。