我有这个咖啡脚本代码,它接受“Enter”按键,以便通过 ajax 提交表单
$(".text_field.comment").keypress (e) ->
if e.which is 13
$(this).blur()
form = $(this).closest("form")
$.ajax
url: form.attr('action')
type: "PUT"
dataType: "json"
data: form.serialize()
false
这里发生的是它重复发送请求近 20 次!!!必须做些什么来停止重复发送请求?
愚蠢的我!答案在于我的控制器。在我有这个之前:
class AnswersController < ApplicationController
before_filter :authenticate_user!
def update
@answer = Answer.find(params[:id])
if @answer.update_attributes(params[:answer])
redirect_to(@answer,
:notice => I18n.t('answer.notice'))
else
flash[:error] = @answer.errors.full_messages.to_sentence
redirect_to @answer
end
end
end
然后我把它改成这样:
class AnswersController < ApplicationController
before_filter :authenticate_user!
def update
@answer = Answer.find(params[:id])
respond_to do |format|
if @answer.update_attributes(params[:answer])
format.json { render :json => @answer }
else
format.json { render :json => @answer.errors.full_messages.to_sentence } #output javascript messages
end
end
end
end
重复请求的原因是因为它有一个“GET /answers/1”的循环请求