首页 > 解决方案 > AJAX Post 方法中的 400 Bad Response Error

问题描述

我正在尝试通过 AJAX 请求向链接添加评论(这是一个使用 Rails 和 JavaScript/JQuery 构建的模拟 Reddit 应用程序)以避免整个页面加载(我不能在此应用程序中使用 remote:true)。

我可以通过 Rails 添加注释并将它们附加到注释列表中,但是当我尝试使用 AJAX 方法时,我收到 400 Bad Request Error。

这是我的脚本:

`

function submitViaAjax() {
    $("#new_comment_button").on("click", function (e) {
        url = this.action
        //var commentText = document.getElementById("comment_body").innerHTML
        //var myJSON = JSON.stringify(commentText);

        data = {
            'authenticity_token': $("input[name='authenticity_token']").val(),
            'comment': {
                'content': $("#comment_body").val()
            }
        };

        console.log(data);

        $.ajax({
            type: "POST",
            url: url,
            data: data,
            headers: { 'Content-Type': 'application/json' },
            success: function (response) {
                var $ul = $("div.comments_section ul");
                $ul.append(response)

            }
        })
        e.preventDefault();
    })
};

这是我的链接显示页面,具有以下形式:

<div class="comments_section">
   <%= render 'comments/comments' %>
</div>

<!--<div id="comments">
</div> -->

<%= simple_form_for [@link, Comment.new]  do |f| %>
  <div class="field">
    <%= f.text_area :body, class: "form-control" %>
  </div>
  <br>
  <%= f.submit "Add Comment", class: "btn btn-primary", id: "new_comment_button", data: { disable_with: false } %>
<% end %>

任何见解将不胜感激。

更新:我的控制器代码,每个请求:

class CommentsController < ApplicationController
  before_action :set_comment, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!

  def index
    if params[:link_id]
      @link = Link.find(params[:link_id])
      @comments = @link.comments
    else
      @comments = Comment.all
    end

    respond_to do |format|
      format.html { render :index }
      format.json { render json: @comments }
    end
  end

  def create
    @link = Link.find(params[:link_id])
    @comment = @link.comments.new(comment_params)
    @comment.user = current_user

    respond_to do |format|
      if @comment.save
        format.html { redirect_to @link, notice: 'Comment was successfully created.' }
        format.json { render json: @comment, status: :created, location: @comment }
        render 'comments/show', :layout => false
      else
        format.html { render action: "new" }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /comments/1
  # DELETE /comments/1.json
  def destroy
    @comment.destroy
    respond_to do |format|
      format.html { redirect_back fallback_location: root_path, notice: 'Comment was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_comment
      @comment = Comment.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def comment_params
      params.require(:comment).permit(:link_id, :body, :user_id)
    end
end

标签: javascriptruby-on-railsajax

解决方案


与@Taplar 所说的相呼应,该元素似乎没有action属性#new_comment_button;这实际上是在某处编码的吗?同样,该action属性必须是您的 AJAX“服务”的确切值——这是否正确设置?


推荐阅读