在我的博客应用程序中,一些帖子显示为摘录——即,用户看到前 500 个字符,并且可以单击链接来查看整个帖子。这是相关的部分:
<% href = url_for post_path(:id => post) %>
<h1 class="title"><%= post.title %></h1>
<h2 class="published_on"><%= post.author %> wrote this <%= time_ago_in_words(post.published_on)%> ago</h2>
<div class="body">
<% if defined?(length) %>
<%= truncate_html(post.body, :length => length, :omission => "…<h1><a class='more' href=\"#{href}\">Click here for more!</a></h1>") %>
<% else %>
<%= post.body %>
<% end %>
</div>
但是,而不是“单击此处了解更多!” 将用户带到一个单独的页面,我希望它可以内联填充帖子的其余部分。目前,我一直在通过将上面的代码片段放在以下 div 中来实现这一点:
<div class="post" id="post_<%= post.id %>">
<%= render :partial => 'post_content', :locals => { :post => post, :length => 500 } %>
</div>
然后我在 application.js 中使用这个 div 的 id 来执行 AJAX:
$(document).ready(function() {
$("a.more").click(function() {
var url = $(this).attr('href');
var id = url.split("/")[2]
$.get(url, null, function(data) {
$("#post_" + id).html(data);
});
return false;
});
});
This is obviously disgusting -- I don't want my javascript to depend on the location of the post's id in the link's href, but I don't know any other way for the javascript to know which post it is getting and therefore into which div the content should be inserted.
What's the best way to accomplish this? Should I just go back to using rails' AJAX helpers?