新手问题 客户端 Ajax 问题

匿名 · 2013年04月29日 · 最后由 gelihai1991 回复于 2013年04月29日 · 2888 次阅读

刚学 rails,今天尝试 ajax 有些疑惑。 从最简单的案例开始,post 下面是 new.html.erb 的代码

<%= form_for(@post) do |f| %>


  <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 %>

在 controller 中的 create 方法

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

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.js {render :layout => false}
        format.json { render json: @post}
      else
        format.html { render action: "new" }
        format.js {render :layout => false, :status => 406}
        format.json { render :json => {:errors => @post.errors.full_messages.join(','), :status=> :unprocessable_entity} }
      end
    end
  end

post.js 代码

$(function(){
    $('#new_post').on('submit', function(event){
        $.ajax({
            url : $(this).prop('action'),
            dataType:'json',
            type:'POST',
            data: $('#new_post').serializeArray(),
            success: function(response){
                alert(response);
            },
            error: function(message){
                var error_message = $.parseJOSN(message);
                alert(message.errors);
            }
        })
    });
})

ajax 不起作用,但是能够创建一个 post,页面跳转...$.ajax 中的 success 的回调函数也不执行...求指导

$('#new_post').on('submit', function(event){
  event.preventDefault(); // <- 加这句

#1 楼 @Rei 你够快,幸好在回复前刷新了一下。

匿名 #3 2013年04月29日

#1 楼 @Rei 谢谢,我是看你写的http://chloerei.com/2012/04/21/rails-3-2-ajax-guide/ 照着写的...

#3 楼 @gelihai1991 这篇看来要更新了…

用好 jquery_ujs 前端几乎是不用写的。

匿名 #6 2013年04月29日

#5 楼 @wushexu 别抢前端的饭碗嘛...呵呵

需要 登录 后方可回复, 如果你还没有账号请 注册新账号