简体   繁体   English

jQuery缺少Rails上Ajax的目标

[英]jQuery missing target for Ajax on Rails

I'm trying to get a new comment form to load under a post. 我正在尝试获取新的评论表格以在帖子下加载。 I have multiple posts on the page so I dynamically create the id's for each post using its primary id. 我在页面上有多个帖子,因此我使用其主要ID为每个帖子动态创建ID。 I then pass that id to my script and I can see in the browser that both the html and the script are being rendered with the correct post id's but for some reason my new comment partial is not being rendered. 然后,我将该id传递给脚本,然后在浏览器中看到html和脚本都使用正确的post id呈现,但由于某种原因,我的新注释部分未呈现。

I'm using jQuery Mobile so I tried targeting the page-content div and it gets rendered fine but it won't render at all when I just try targeting the div that contains my post. 我使用的是jQuery Mobile,所以我尝试定位到页面内容div,它可以很好地呈现,但是当我尝试定位包含我的帖子的div时,它根本无法呈现。 Its as if the id doesn't exist but I can see it when I view source. 好像id不存在,但查看源代码时可以看到它。 Is there an issue with targeting dynamically created id's or is there some kind of trick to it? 定位动态创建的ID是否存在问题,还是有一些技巧?

Here is my javascript: 这是我的JavaScript:

$("#post_<%= escape_javascript(@post.id.to_s) %>").append("<%= escape_javascript(render "comments/new", item: :post) %>");

My action: 我的动作:

def load_new_comment_partial
  @comment = Comment.new
  @post = Post.find(params[:id])
  respond_to do |format|
    format.js { render "comments/new" }
  end
end

This js code is tricky sometimes, you can try this: 这段js代码有时很棘手,您可以尝试以下方法:

$('<%= "#post_#{@post.id.to_s}" %>').append('<%= escape_javascript(render "comments/new", item: @post) %>');

That code above should be on load_new_comment_partial.js.erb 上面的代码应该在load_new_comment_partial.js.erb上

I've changed the quotation and also the item param I've changed to @post instead of :post 我更改了引号,并将项目参数更改为@post而不是:post

And in your action you can replace 而在您的行动中,您可以替换

format.js { render "comments/new" }

with

format.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM