【问题标题】:Why is my comment being rendered as a JSON object and not appended to the DOM为什么我的评论被呈现为 JSON 对象而不是附加到 DOM
【发布时间】: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


【解决方案1】:

我无法确认您的其余代码是否正常工作,但您需要手动处理 submit 事件以防止页面重新加载...

$("#new_comment").on("submit", function(e) {
   e.preventDefault();

   ....

【讨论】:

    【解决方案2】:

    submit event 重新加载页面。要阻止它重新加载页面,prevent its default action。所以,你的第一个函数看起来像:

    $(function createComment() {
      $("#new_comment").on("submit", function(e) {
    
        e.preventDefault();
    
        const values = {
          description: $('#comment_description').val(),
          rating: $('#comment_rating').val()
        };
    
        const newComment = new Comment(values);
        newComment.commentConfirm();
    
      });
    });
    

    【讨论】:

    • @cantuke 因此,当我添加 preventdefault 时,页面上没有任何反应,并且我在控制台“404”中收到路由错误,没有路由匹配,我知道我之前尝试过,但没有运气。
    • 我注意到您将 $.post 与未在任何地方定义的操作一起使用。检查它到达的 url 是否可以访问,并且它正在做它应该做的事情。不幸的是,在 Ruby 方面我帮不了你。
    • 还要检查上面@James 的评论,因为它不再重新加载页面,它可以帮助您调试它的去向
    • @James 该请求似乎在开发工具中运行良好,状态 200 正常,它只是重定向到另一个页面,而不是停留在配方页面上。似乎它在整个过程中根本没有到达 $.post 代码,不知道为什么它没有......尝试添加调试器但没有运气。
    猜你喜欢
    • 1970-01-01
    • 2015-12-01
    • 2019-07-20
    • 2015-03-21
    • 2022-01-21
    • 2014-06-11
    • 2021-01-06
    • 2020-08-10
    • 2019-08-15
    相关资源
    最近更新 更多