简体   繁体   中英

Rails 3.1 Ajax question

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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