我正在尝试通过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
答案 0 :(得分:0)
与@Taplar所说的相呼应,action
元素似乎没有#new_comment_button
属性;这实际上是在某处编码的吗?同样,该action
属性必须是您的AJAX“服务”的确切值-这样设置正确吗?