最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Rails 3.1 Ajax question - Stack Overflow

programmeradmin1浏览0评论

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
发布评论

评论列表(0)

  1. 暂无评论