javascript - 在 Rails 应用程序中提前输入 : Append JSON request to only one specific request instead of appending JSON request to every request via prefetch

标签 javascript ruby-on-rails ruby json twitter-typeahead

提前输入功能可以正常工作。但问题是,提前输入功能会在每个数据请求上发出 JSON 请求,而实际上只应针对一个特定请求发生。

我有以下 Controller :

#controllers/agencies_controller.rb
class AgenciesController < ApplicationController

  def get_unique_agency_names
    @unique_agency_names = Agency.uniq.pluck(:name)
    respond_to do |format|
      format.json { render json: @unique_agency_names }
    end
  end
  ...
end

我的 javascript 文件中有以下内容:

#app/assets/javascripts.agencies/index.js
$(document).ready(function(){
  /* For typeahead functionality on name input of search form for agencies */
  var agency_names = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: '../agencies/get_unique_agency_names.json'
  });

  $('#prefetch .typeahead.name_input').typeahead(null, {
    name: 'agency_names',
    source: agency_names
  });
});

为了完成,这里是我希望实现此功能的地方:以这种形式:

# just showing the relevant part of the form
<div class="form-group" id="prefetch">
  <%= f.label :name_cont, "Agency Name" %>
  <%= f.text_field :name_cont, class: "form-control typeahead name_input", placeholder: "Enter Agency Name" %>
</div>

这是我在 config/routes.rb 中的相关路线

resources :agencies do
  collection do
    get 'get_unique_agency_names'
  end
end

我的具体问题是:如何确保 GET "/agencies/get_unique_agency_names" 只在应该调用时调用?现在它正在为每个请求附加这个 JSON 请求。我只希望针对一个特定请求发生 JSON 请求。

Twitter's Type Ahead Examples

最佳答案

我想你需要这个

  $('#prefetch .typeahead.name_input').typeahead(null, {
    generateOnLoad:false,
    name: 'agency_names',
    source: agency_names
  });

generateOnLoad {boolean}

空(默认)

如果启用,将在页面加载时生成源数据(执行 Ajax 请求并准备要搜索的数据),而不是等待输入获得焦点。

PN:此选项不适用于 dynamic: true 除非调整了一些其他配置。

此外,如果您发现 Rails list 文件将您的调用添加到每个页面,只需在预先输入绑定(bind)之前检查元素是否存在:

if($('#prefetch .typeahead.name_input').length){
      $('#prefetch .typeahead.name_input').typeahead(null, {
        generateOnLoad:false,
        name: 'agency_names',
        source: agency_names
      });
}

关于javascript - 在 Rails 应用程序中提前输入 : Append JSON request to only one specific request instead of appending JSON request to every request via prefetch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33834219/

相关文章:

php - 如何使用 AJAX 更新选择菜单 w/out <div> inside form

javascript - 在表中保存和显示 Cookie

javascript - 如何比较 Cappuccino 中的两个对象是否相等

ruby-on-rails - 事件记录 :includes - how to use map with loaded associations?

ruby-on-rails - LearnRubyTheHardWay Ex#46 - rake 中止,你应该需要 'minitest/autorun'

javascript - 用Javascript中设置的字典数组替换字符串中的字母

ruby-on-rails - 测试 Rails 应用程序的 Braintree 透明重定向

ruby-on-rails - 如何在 Rails 3 中使用 Draper 装饰嵌套属性(关联)?

ruby-on-rails - 带有 Rails 3.0 的 Google map API

ruby-on-rails - ruby rails : short hand to put commas in between elements in an array?