0
我有一個接受「回車」按鍵,以通過Ajax提交表單這個CoffeeScript的代碼咖啡上輸入按鍵時重複發送PUT請求
$(".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 /答案/ 1」
恐怕它仍然是一樣的錯誤。 – neilmarion 2013-04-24 00:16:46
@neilmarion - 哪個錯誤?你說這是反覆提交。現在只應在每次註冊關鍵事件時提交(大多數情況下每封信一次)。 – 2013-04-24 00:18:07
它仍然重複發送請求。試圖通過console.log輸出,但它只打印一次。所以可能重複的按鍵已經被整理出來,但發送ajax請求時有些奇怪。 – neilmarion 2013-04-24 00:21:20