Rails和Jquery Ajax


I follow this tutorial (except I put gem 'jquery-rails' in my gemfile ).

The problem, if I click to new post, and fill the form and click to create -> ajax don't work, and show method showing the simple post.

my create.js.erb:

$('body').html("<h1><%= escape_javascript(@post.title) %></h1>").append("<%= escape_javascript(@post.content) %>");

create method

def create
@post = Post.new(params[:post])

respond_to do |format|
  if @post.save
    format.html { redirect_to(@post, :notice => 'asdasd') }
    format.js
  else
    format.html { render :action => "new" }
    format.js
  end
end

end

_form.html.erb

    <%= form_for(@post, :remote => true) do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br />
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

That's because you're replacing the entire body of your page with the contents

<h1><%= escape_javascript(@post.title) %></h1>

You probably want to append it to some kind of place holder like so

$('#postlist').append('a bunch of html')

Check out the DOM manipulation methods here.