渲染.json.erb模板时不调用jQuery .done

时间:2017-07-16 14:20:34

标签: javascript jquery ruby-on-rails json ruby

我试图通过将响应从create移动到视图来清理代码(使用了一些帮助程序,这很有意义)。但是出于某种原因,我的js回调永远不会被调用。我100%困惑,所以这里是我的日志和代码。非常感谢: - )

reviews_controller.rb

def create
    @review = Review.new(post_params)
    @review.library = @library if @library
    @review.user = current_user
    if !@review.save
        render json: {error_code: "400", message: "Invalid paramaters"}
    end
    respond_to do |format|
        format.html {redirect_to(library_path(@library))}
        format.json {render "create.json"}
    end
end

libraries.js(在页面上加载)

$(document).ready( function(){
    $("#new_review").submit(function(event) {
        event.preventDefault();

        var form = $(this);

        var values = form.serialize();
        var url = form.attr("action");
        debugger;
        $.post(url + ".json", values).done(function(data) {
            debugger;
        });
    });
});

create.json.erb

{
    review: <%= @review.to_json %>, 
    average_rating: <%= number_to_human(@library.average_rating) %>
}

服务器日志

Started POST "/libraries/10/reviews.json" for 127.0.0.1 at 2017-07-16 10:12:18 -0400
Processing by ReviewsController#create as JSON
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"MgB1pj2lQNMgPCknUMP+lc2EWtrp06n1GkaAbrJONJwM//fmY7gI8azvy3IFh9NZfoRysoiVln3vAH+AFzW1QQ==", "review_rating_dispaly"=>"1", "review"=>{"rating"=>"1", "comment"=>""}, "library_id"=>"10"}
  Library Load (0.2ms)  SELECT  "libraries".* FROM "libraries" WHERE "libraries"."id" = ? LIMIT 1  [["id", 10]]
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
   (0.1ms)  begin transaction
  SQL (0.3ms)  INSERT INTO "reviews" ("comment", "library_id", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["comment", ""], ["library_id", 10], ["user_id", 1], ["created_at", "2017-07-16 14:12:18.075609"], ["updated_at", "2017-07-16 14:12:18.075609"]]
   (5.6ms)  commit transaction
   (0.1ms)  SELECT AVG("reviews"."rating") FROM "reviews" WHERE "reviews"."library_id" = ?  [["library_id", 10]]
  Rendered reviews/create.json.erb (1.8ms)
Completed 200 OK in 16ms (Views: 4.2ms | ActiveRecord: 6.4ms)
来自Chrome网络日志中服务器的

响应

{
    review: {&quot;id&quot;:37,&quot;rating&quot;:1,&quot;user_id&quot;:1,&quot;library_id&quot;:10,&quot;comment&quot;:&quot;&quot;,&quot;created_at&quot;:&quot;2017-07-16T14:23:25.213Z&quot;,&quot;updated_at&quot;:&quot;2017-07-16T14:23:25.213Z&quot;}, 
    average_rating: 1.86
}

1 个答案:

答案 0 :(得分:0)

在行定义之前添加",并将.html_safe添加到json

{
    "review": <%= @review.to_json(only: [:comment, :rating]).html_safe %>,
    "average_rating": <%= number_to_human(@library.average_rating) %>
}