【发布时间】:2019-02-15 22:11:24
【问题描述】:
我正在使用 Jquery 创建评论,并希望将其附加到页面而不重新加载页面。我有一个commentConfirm 原型函数在发布之前捕获它。我不能在这个项目上使用 remote:true 所以这里是代码:
$(function createComment() {
$("#new_comment").on("submit", function(e) {
const values = {
description: $('#comment_description').val(),
rating: $('#comment_rating').val()
};
const newComment = new Comment(values);
newComment.commentConfirm();
});
});
function Comment(comment) {
this.description = comment.description;
this.rating = comment.rating;
}
Comment.prototype.commentConfirm = function(e) {
let doIt = confirm(`You are about to comment: "${this.description}" and give a rating of: ${this.rating} stars`);
if(!doIt)
return;
let params = {
'comment[description]': this.description,
'comment[rating]': this.rating
};
$.post(this.action, params).success(function(response) {
$('div.comments_container').append('<div class="new_comment_' + `${response.id}` + '"> </div>')
$('div.new_comment_'+ `${response.id}`).append('<h3 class="cheading">' + `${response.user.name}` + ' gives ' + `${response.rating}` + ' out of 5 stars! </h3>')
$('div.new_comment_'+ `${response.id}`).append('<p class="cdescription">' + `${response.description}` + '</p>')
$('div.new_comment_'+ `${response.id}`).append('<a class="ecomment" href="/recipes/' + `${response.recipe_id}` + '/comments/' + `${response.id}` + '/edit">Edit</a>' + " ")
$('div.new_comment_'+ `${response.id}`).append('<a class="dcomment" rel="nofollow" data-method="delete" href="/comments/' + `${response.id}` + '">Delete</a>')
$('form#new_comment')[0].reset();
});
};
不确定这是否会导致问题,但这是我在控制器中的创建函数:
def create
if logged_in?
comment = Comment.new(comment_params)
comment.recipe = find_by_recipe_id
comment.user = current_user
if comment.description.empty? || comment.rating == nil
redirect_to recipe_path(comment.recipe), alert: "Please fill out all fields"
else
comment.save
render json: comment.to_json(only: [:rating, :description, :id, :recipe_id],
include: [user: { only: [:name]}])
end
else
redirect_to login_path, alert: "You must be logged in to comment"
end
end
对他的问题的任何帮助将不胜感激!
如果这有助于回答一些其他问题,这里是 repo:https://github.com/Bartekswistak/fun_guy_chef/tree/jquery
【问题讨论】:
-
您需要检查您的后端代码是否正常工作。导致 ajax 请求发生,然后检查您的浏览器开发人员工具网络选项卡并确保 ajax 响应看起来正确。
-
@james 这一切都很好,但是我需要将原型添加到这个应用程序中,所以添加它并移动东西已经破坏了它。当我添加 preventDefault 时,它根本不起作用,并且代码原样,它重新加载页面并以 JSON 格式显示评论,而不是像以前那样直接附加它。
标签: javascript jquery ruby-on-rails ajax