我不知道它究竟是如何调用的,但作为一个例子。
我有可能创建帖子,我有2个按钮 - “保存”和“预览”。
我希望当用户点击“预览”用户不离开页面时,但是使用JS时它会在按钮新的html后发布,并带有后期视图。
你能告诉我它是如何完成的吗?
答案 0 :(得分:0)
让我们假设...如果你想点击按钮旁边的点击预览按钮来预览帖子,那么它应该是这样的......
您的观点
<a href="<%= preview_path(@post)%>" id="show_preview" data-post_id="<%= @post.id%>"> title="click to preview this post">
Preview
</a>
<button type="submit">Submit</button>
<!-- this is the container that will show the preview post -->
<div id="preview_container">
</div>
在view.js脚本中。
$("#show_preview").on("click",function(){
//call ajax to show preview of the post in the preview container
var post_id = $(this).data("post_id");
//this is the show call to posts_controller#show
$.ajax({
url: "/posts/'"+post_id,
beforeSend: function( xhr ) {
//change text of a tag to loading
}
})
.done(function( data ) {
});
})
在posts_controller.rb中
def show
##you might already be using id param to get post
@post = Post.find(param[:id])
##dont wory about rendering show.js.erb,rails will understand what type of request is it and then render show.html.erb or show.js.erb.so just create show.js.erb to replace and fill the preview container
end
在posts / show.js.erb 中
希望这就是你所期待的:)/ ##just render _show.html.erb inside the container
$("#preview_container").html("<%= escape_javascript(render(:partial => 'post/show.html.erb' %>");
write you html in _show.html.erb that will be shown in the preview_container