渲染 .json.erb 模板时不调用 jQuery .done
Posted
技术标签:
【中文标题】渲染 .json.erb 模板时不调用 jQuery .done【英文标题】:jQuery .done is not called when rendering .json.erb template 【发布时间】:2017-12-21 03:02:48 【问题描述】:我试图通过将响应从创建移动到视图来清理代码(使用了一些帮助程序,这是有道理的)。但是由于某种原因,我的 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: "id":37,"rating":1,"user_id":1,"library_id":10,"comment":"","created_at":"2017-07-16T14:23:25.213Z","updated_at":"2017-07-16T14:23:25.213Z",
average_rating: 1.86
【问题讨论】:
您在网络控制台上得到的响应是什么? 编辑的答案显示。它似乎返回了正确的数据,但不会调用.done
:-(
这不是有效的 JSON
不应该调用done
吗?
很可能它试图将其解析为 JSON 并且失败了,因此不会调用 done
而调用 fail
。
【参考方案1】:
在行定义前添加"
,并在json中添加.html_safe
"review": <%= @review.to_json(only: [:comment, :rating]).html_safe %>,
"average_rating": <%= number_to_human(@library.average_rating) %>
【讨论】:
以上是关于渲染 .json.erb 模板时不调用 jQuery .done的主要内容,如果未能解决你的问题,请参考以下文章
为啥在组件加载时不调用 useEffect(()=...,[]) ?