[英]400 Bad Response Error in AJAX Post Method
我正在尝试通过AJAX请求向链接(这是使用Rails和JavaScript / JQuery构建的模拟Reddit应用程序)中添加注释,以避免整个页面加载(我不能在此应用程序中使用remote:true)。
我可以添加注释,并通过Rails将注释列表附加到它们的后面,但是当我尝试使用AJAX方法时,出现400错误的请求错误。
这是我的脚本:
`
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
与@Taplar所说的相呼应,# #new_comment_button
元素似乎没有action
属性。 这实际上是在某处编码的吗? 同样,该action
属性必须是您的AJAX“服务”的确切值-是否正确设置?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.