咖啡在输入键上反复发送PUT请求

时间:2021-11-04 09:23:24

I have this coffeescript code that accepts an "Enter" keypress in order to submit a form through ajax

我有这个coffeescript代码,它接受一个“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

What happens here is that it repeatedly sends the request for almost 20 times!!! What must be done to stop repetitive sending of request?

这里发生的是它重复发送请求近20次!!必须怎样做才能停止重复发送请求?

Stupid me! The answer lies in my controller. Before I have this:

愚蠢的我!答案就在我的控制器上。之前我有这个:

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

Then I changed it to this:

然后我把它改成了这个:

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

The reason for the repeated requests is because it's having a circular request of "GET /answers/1"

重复请求的原因是它有一个循环请求“GET /answers/1”

1 个解决方案

#1


0  

"The keypress event is sent to an element when the browser registers keyboard input." -jQuery API

“当浏览器注册键盘输入时,按键事件被发送到一个元素。”jquery API

What this means for your case is that you are constantly encountering keyboard input and running that function. I believe what you may have been after was keyup.

这对您的情况意味着,您不断地遇到键盘输入并运行该函数。我相信你可能一直在寻找的是keyup。

$(".text_field.comment").keyup (e) ->

#1


0  

"The keypress event is sent to an element when the browser registers keyboard input." -jQuery API

“当浏览器注册键盘输入时,按键事件被发送到一个元素。”jquery API

What this means for your case is that you are constantly encountering keyboard input and running that function. I believe what you may have been after was keyup.

这对您的情况意味着,您不断地遇到键盘输入并运行该函数。我相信你可能一直在寻找的是keyup。

$(".text_field.comment").keyup (e) ->