【问题标题】:Update Rails instance variable after ajax callajax 调用后更新 Rails 实例变量
【发布时间】:2018-06-23 00:10:43
【问题描述】:

我正在尝试让用户输入 ISBN 号并接收有关该图书的数据。这在用户第一次输入 ISBN 编号时有效,但当他/她尝试更改它时,该值无法更新(尝试更改该值后,它会自行更改回第一个 ISBN 编号)。

我有一个_form.html.erb 部分,当在input#isbn_field 中输入某些内容时会更新它。如果 ISBN 有效,则更新 info 以将 div 中的其他信息(作者姓名、标题等)替换为 id: 'isbn-lookup-results-container'

如何在 isbn_lookup_result 部分加载后更改 ISBN?

listings_controller.rb

def lookup
   @listing = Listing.new
   @isbn_lookup_result = Listing.amazon_lookup(params[:isbn])
   render partial: 'isbn_lookup_result'
  end

lookup.js.coffee

$(document).ready ->
  TIMEOUT = null
  $(document).on 'keyup', 'input#isbn_field', ->
    clearTimeout TIMEOUT
    TIMEOUT = setTimeout((->
      ajaxResponse = $.ajax(
        url: '/listings/lookup'
        type: 'GET'
        data:
          isbn: $('input#isbn_field').val())
      ajaxResponse.success (data) ->
        $('#isbn-lookup-results-container').html data
        $('#form-unfilled').hide()
        return
      ajaxResponse.error (data) ->
        alert 'Not a valid ISBN'
        return
      return
    ), 2000)
    return
  return

_isbn_lookup_result.html.erb

<%= form_for(@listing, :html => {class: "form-horizontal" , 
    role: "form"}, method: :get) do |f| %>
       <div class="form-group">
        <%= f.text_field :isbn , class: "form-control" , 
              id: "isbn_field", placeholder: "ISBN (10 or 13 digits - no dashes)",         
              value: @isbn_lookup_result[:isbn], autofocus: true %>
        </div>
        # More stuff
<% end %>

【问题讨论】:

    标签: ruby-on-rails ajax coffeescript


    【解决方案1】:

    如果我对您的理解正确,并且我想我是这样,那么您只是遇到了 javascript 问题。

    现在,当页面加载时,您将事件绑定到 DOM 中的选择器。相反,您希望根据事件绑定到文档的body 及其内容。

    我会尝试用$('body').on 'keyup', 'input#isbn_field', 替换$(document).on 'keyup', 'input#isbn_field',

    比我更聪明的人在这里讨论这个Jquery Event won't fire after ajax call — 一个好的 Google foo 将类似于 ajax 之后的绑定事件

    【讨论】:

    • 即使我这样做了,我的 rails 控制台也没有显示正在发送另一个 get 请求(并且原始 isbn 替换了我添加的任何新请求)。基于我的 javascript,我怎样才能使它即使在初始 AJAX 调用之后也可以发送另一个 get 请求?
    • 你能在 Github 上举个例子吗?
    • Josh,here 是该问题的存储库。您需要拥有自己的 Amazon 请求访问密钥。
    • Here 是获取您自己的访问密钥的链接。
    • 在那个 repo 的问题中删除了一些注释。
    猜你喜欢
    • 2019-02-01
    • 2013-10-11
    • 2019-10-21
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 2015-01-18
    • 1970-01-01
    相关资源
    最近更新 更多