2017-05-07 73 views
2

Iam在Rails中構建表單。我希望通過AJAX提交,所以我設置好的remote: true如何從事件ajax的響應中獲取數據:Rails 5.1中的錯誤

<%= form_for @post, html: { multipart: true }, remote: true do |f| %> 
    ... 
<%= end %> 

在我的控制器:

def create 
    @post = Post.new(post_param) 

    respond_to do |format| 
     if @post.save 
      format.html { redirect_to @post, notice: 'Post was successfully created.' } 
      format.json { render :show, status: :created, location: @post } 
     else 
      format.html { render json: @post.errors, status: 400 } 
      format.json { render json: @post.errors, status: 400 } 
     end 
    end 
end 

在表格上視圖

$('#new_post').on('ajax:success', function(data) { 
    console.log(data); 
}).on('ajax:error', function(evt, xhr, status, error) { 
    console.log(xhr); 
}); 

但事件 'AJAX:錯誤',我無法解析以獲取有關帖子驗證錯誤的數據。所有params'xhr','status','error'都等於undefined。

如何解析'ajax:error'中的響應以獲取有關驗證錯誤的數據?

回答