admin管理员组

文章数量:1410682

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?

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?

Share asked Jun 19, 2011 at 23:26 DudeGuySomeTimeDudeGuySomeTime 431 silver badge4 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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>"); 

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

本文标签: javascriptRails 31 Ajax questionStack Overflow