简体   繁体   English

AJAX发布方法中的400错误响应错误

[英]400 Bad Response Error in AJAX Post Method

I'm trying to add a comment to a link (this is a mock Reddit application built with Rails and JavaScript/JQuery) through an AJAX request to avoid an entire page load (I can't use remote: true in this application). 我正在尝试通过AJAX请求向链接(这是使用Rails和JavaScript / JQuery构建的模拟Reddit应用程序)中添加注释,以避免整个页面加载(我不能在此应用程序中使用remote:true)。

I'm able to add comments and append them the list of comments through Rails, but when I try to use the AJAX method, I get a 400 Bad Request Error. 我可以添加注释,并通过Rails将注释列表附加到它们的后面,但是当我尝试使用AJAX方法时,出现400错误的请求错误。

Here's my script: 这是我的脚本:

` `

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();
    })
};

And here's my Links show page that has the form: 这是具有以下形式的“链接”显示页面:

<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 %>

Any insight would be greatly appreciated. 任何见识将不胜感激。

UPDATE: My controller code, per request: 更新:我的控制器代码,每个请求:

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

Echoing what @Taplar said, there does not look to be an action attribute for the #new_comment_button element; 与@Taplar所说的相呼应,# #new_comment_button元素似乎没有action属性。 is this actually encoded somewhere? 这实际上是在某处编码的吗? As well, that action attribute has to be the exact value of your AJAX 'service' - is this correctly set up? 同样,该action属性必须是您的AJAX“服务”的确切值-是否正确设置?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM