简体   繁体   English

Rails 3.1 Ajax问题

[英]Rails 3.1 Ajax question

I have a scaffold called post which has a title and a description. 我有一个名为post的脚手架,它有标题和描述。 On my layout I have a link to create a new post that has :remote => true. 在我的布局上,我有一个链接来创建一个新帖子: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? 当我点击远程链接更改div的内容以便我可以创建新帖子时,我该如何制作?

Let's suppose the action you will use is called new . 我们假设您将使用的操作称为new You should create a file called new.js.erb into views/posts that will be rendered when you post remotely your form. 您应该将一个名为new.js.erb的文件创建到远程发布表单时将呈现的视图/帖子中。 That file must include the javascript that places the new post into the div you want to fill. 该文件必须包含将新帖子放入要填充的div中的javascript。 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. 在ajax帖子完成并创建新帖子后,javascript将立即执行。 Remember the following: - You have to include jQuery - You have to specify in posts_controller the ability to render .js format, something like 请记住以下内容: - 您必须包含jQuery - 您必须在posts_controller中指定呈现.js格式的能力,类似于

# 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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