我有一个名为 post 的脚手架,它有一个标题和一个描述.在我的布局上,我有一个链接可以创建一个具有 :remote => true 的新帖子.当我单击该远程链接以更改 div 的内容以便创建新帖子时,我将如何做到这一点?
I have a scaffold called post which has a title and a description. On my layout I have a link to create a new post that has :remote => true. How would I make it when I click on that remote link to change the content of a div so that I can create a new post?
假设您将使用的操作名为 new
.您应该在视图/帖子中创建一个名为 new.js.erb
的文件,该文件将在您远程发布表单时呈现.该文件必须包含将新帖子放入要填充的 div 的 javascript.例如,它可能包含
Let's suppose the action you will use is called new
.
You should create a file called new.js.erb
into views/posts that will be rendered when you post remotely your form. That file must include the javascript that places the new post into the div you want to fill. As an example, it could contain
# new.js.erb
$('div#container').html("<p><%= escape_javascript(@post.title) %></p>").append("<p><%= escape_javascript(@post.content) %></p>");
ajax 帖子完成并创建新帖子后,javascript 将立即执行.请记住以下内容:- 你必须包括 jQuery- 您必须在 posts_controller 中指定呈现 .js 格式的能力,例如
The javascript will be executed immediately after the ajax post is finished and the new post is created. Remember the following: - You have to include jQuery - You have to specify in posts_controller the ability to render .js format, something like
# posts_controller.erb
def create
@post = Post.new(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to(@post, :notice => 'Post created via non AJAX.') }
format.js # the actual ajax call
else
format.html { render :action => "new" }
end
end
end
这篇关于Rails 3.1 Ajax 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!