【问题标题】:Dynamic update with method calling to Amazon API通过调用 Amazon API 的方法进行动态更新
【发布时间】:2017-09-17 07:55:11
【问题描述】:

我是 Rails 的初学者,但我对此进行了很多搜索,但似乎无法找到可以帮助我的东西,因为我很难解决问题。我已经建立了一个工作方法,它从亚马逊请求关于给定 ISBN 的书的信息,现在想在用户将 ISBN 输入表单后使用它来自动填充有关该书的信息。这是我的方法(在我的 Listing.rb 模型文件中):

def self.isbn_lookup(val)
  request = Vacuum.new('US')
  request.configure(
  aws_access_key_id: 'access_key_here',
  aws_secret_access_key: 'secret_access_key_here', 
  associate_tag: 'associate_tag_here' 
)
  response = request.item_lookup(
    query: {
      'ItemId' => val,
      'SearchIndex' => 'Books',
      'IdType' => 'ISBN'
  },
    persistent: true
)
  fr = response.to_h #returns complete hash
  author = fr.dig("ItemLookupResponse","Items","Item","ItemAttributes","Author")
  title = fr.dig("ItemLookupResponse","Items","Item","ItemAttributes","Title")
  manufacturer = fr.dig("ItemLookupResponse","Items","Item","ItemAttributes","Manufacturer")
  url = fr.dig("ItemLookupResponse","Items","Item","ItemLinks","ItemLink",6,"URL")

    return {title: title, author: author, manufacturer: manufacturer, url: url}

  end

这里是我的控制器。我不确定如何使这个通用化,以便 ISBN 编号依赖于用户输入的内容(它应该采用用户给出的值,而不是假设始终设置 @isbn 实例变量):

def edit
  @isbn = Listing.isbn_lookup(1285741552)
end

这是我的 _form.html.erb 部分,我想在其中调用此 ISBN 自动填充:

  <%= form_for(@listing, :html => {class: "form-horizontal" , role: "form"}, method: :get) do |f| %>
<div class="form-group">
  <div class="control-label col-sm-2">
    <%= f.label :isbn, "ISBN" %>
  </div>
  <div class="col-sm-8">
    <%= f.text_field :isbn, id: "auto-isbn", class: "form-control" , placeholder: "ISBN (10 or 13 digits)", autofocus: true %>
  </div>
</div>
...
<% end %>

最后,这是我认为应该是 AJAX 调用开始的 JS:

 $(document).ready(function() {
  $(document).on('keyup','input#auto-isbn',function() {
    $.get(this.action, $(this).serialize(), null, "script");
    return false;
  });
});

如何让用户输入 ISBN 时,我的应用会调用 isbn_lookup 方法,然后返回收集到的信息?

【问题讨论】:

  • 你在使用 JQuery 吗?还是只是普通的 JS?
  • 我正在使用 jQuery

标签: ruby-on-rails ajax


【解决方案1】:

首先,我将在您的 routes.rb 文件中创建一个 lookup 路径。这看起来像:

resources :listings do 
  collection do 
    get :lookup
  end
end

这会给你:

lookup_listings GET    /listings/lookup(.:format)     listings#lookup

然后在listings_controller.rb 中创建lookup 操作,类似于:

class ListingsController < ApplicationController

  ...

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

  ...

end

当然,这要求您有一个 _isbn_lookup_result.html.erb 文件来访问/使用来自 @isbn_lookup_result 的值。

然后,要从您的 JS 调用此操作,请执行以下操作(完全公开,我使用的是咖啡脚本,所以我的普通 JS 技能有点生疏):

$(document).ready(function() {
  @TIMEOUT = null

  $(document).on('keyup','input#auto-isbn',function() {
    clearTimeout(@TIMEOUT)
    @TIMEOUT = setTimeout(function(){
      var ajaxResponse = $.ajax({
        url: "listings/lookup",
        type: 'GET',
        data: {isbn: $('input#auto-isbn').val()}
      });
      ajaxResponse.success(function(data){
        # do stuff with your data response
        # perhaps something like:
        $('#isbn-lookup-results-container').html(data)
      });
    }, 500);
  });

});

这一点:

  clearTimeout(@TIMEOUT)
  @TIMEOUT = setTimeout(function(){
    ...
  }, 500);

在用户停止输入和调用 ajax 函数之间产生 1/2 秒的延迟。这样一来,您就不会真的在 每个 keyup 上进行查找,只有当用户暂停输入时。

这一点:

var ajaxResponse = $.ajax({
  url: "listings/lookup",
  type: 'GET',
  data: {isbn: $('input#auto-isbn').val()}
});

是 AJAX 调用。您可以看到正在使用的新 listings/lookup 路径。 data: {isbn: $('input#auto-isbn').val()} 位为您提供params[:isbn],在lookup 操作中使用。

然后,在成功后,您可以使用此位来处理您的响应:

ajaxResponse.success(function(data){
  # do stuff with your data response
  # perhaps something like:
  $('#isbn-lookup-results-container').html(data)
});

在这种情况下,data 是由 render partial: 调用产生的 HTML,因此可以将其加载到 div 中。

【讨论】:

  • 这是一个很好的开始,正是我想要的!谢谢。
  • 超级!乐意效劳。事实上,我创建了自定义 JQuery 插件来处理这样的事情,因为我觉得它可以帮助我更有效地组织我的代码。我很想展示如何做到这一点,但我所有的东西都在咖啡脚本中,我担心我会得到简单的 JS 语法错误,这只会让事情变得混乱。
  • 在我的视图 > 列表文件夹中是否需要一个 lookup.html.erb 文件?
  • 我在发表评论后就明白了。感谢您的澄清!
  • 那个错误是在你的浏览器控制台中,我想?您需要查看您的 rails 控制台以了解那里发生了什么。
猜你喜欢
  • 2012-06-19
  • 1970-01-01
  • 2013-09-23
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多