rails远程表单和jquery

时间:2016-08-26 09:36:27

标签: javascript ruby-on-rails ajax coffeescript

使用rails 4.2.6,coffee-rails 4.1.0,jquery-rails 4.1.1。 有一个远程表单:true

我的.slim视图

div class="throughputs_update"
  = form_tag("/proxyz/throughputs/#{host['throughputs'][proxy_type]['id']}", method: :put, remote: true) do
    div class="row"
      div class="col-xs-6"
        div class="input-group"
          = number_field_tag :amount, host['throughputs'][proxy_type]['amount'], min: 0, class: "form-control"
          span class="input-group-btn"
            = button_tag nil, type:"submit", class:"btn btn-default"
              span class="glyphicon glyphicon-ok"

使用html:

<div class="throughputs_update">
  <form action="/proxyz/throughputs/1" accept-charset="UTF-8" data-remote="true" method="post">
    <input name="utf8" type="hidden" value="✓">
    <input type="hidden" name="_method" value="put">
    <div class="row">
      <div class="col-xs-6">
        <div class="input-group">
          <input type="number" name="amount" id="amount" value="1" min="0" class="form-control">
          <span class="input-group-btn">
            <button name="button" type="submit" class="btn btn-default">
              <span class="glyphicon glyphicon-ok">
              </span>
            </button>
          </span>
        </div>
      </div>
    </div>
  </form>
</div>

in .coffee

ready = ->
  console.log "first"
    jQuery ->
    $(document)
      .on "ajax:success", ".throughputs_update", ->
        console.log "ajax:success"
      .on "ajax:complete", ".throughputs_update", ->
        console.log "ajax:complete"
      .ajaxSend ->
        console.log "ajax send"
      .ready ->
        console.log "ready!"

$(document).ready(ready)
$(document).on('page:load', ready)

在我的控制器中:

  def update
    ...
    render json: @host, status: :ok
  end

提交表单后,它不起作用,没有任何功能。唯一的console.log:

first
ready!

并没有错误。 在rails控制台中:

Started PUT "/proxyz/throughputs/3" for 127.0.0.1 at 2016-08-26 12:18:30 +0300
Processing by Proxyz::ThroughputsController#update as JS
  Parameters: {"utf8"=>"✓", "amount"=>"1", "button"=>"", "id"=>"3"}
...
Completed 200 OK in 7ms (Views: 0.2ms | ActiveRecord: 0.0ms)

为什么会这样?

1 个答案:

答案 0 :(得分:0)

嘿所以我认为将.on "ajax:success"绑定到包裹表单的div(".throughputs_update")是错误的。我敢打赌,如果你拿出".throughputs_update"并且只有.on "ajax:success" ->它会起作用。或者,如果您真的想要绑定到该表单,则可以使用绑定到按钮标记的click事件。如果您在提交表单时提供了有关您想要执行的操作的更多详细信息,则可能有人能够描述这样做的好方法。