【问题标题】:Twitter Bootstrap Typeahead gon gem and passing data from model into JS - in json formatTwitter Bootstrap Typeahead gon gem 并将数据从模型传递到 JS - 以 json 格式
【发布时间】:2012-04-14 12:18:15
【问题描述】:

我希望将我的“公司”的名称传递到表单上的自动完成预输入中。

我正在使用 twitter bootstrap 和 gon gem 将数据传递到 Json 并使其可用于 js。

但是我无法让该字段响应,我不认为数据可用于表单并且不明白为什么。

我的公司控制器执行以下操作,将公司名称分配给 gon 变量。

gon.firms = Firm.all.map &:name

我的 Application.html.erb 在其标头中有以下内容,以使 gon 变量可用于 js。

<%= include_gon %>
<script type="text/javascript">
    jQuery(document).ready(function() {
        $(.typeahead).typeahead({source:gon.firms});
    });
    </script>

然后我有我想要分配 typeahead 的表单,我已经分配了 class="typeahead" 给它。

<%= form_tag firms_path, :method => 'get', :class => 'typeahead'  do %>
<%= text_field_tag :search, params[:search], :class => 'input-medium search-query', :placeholder => 'Firm name' %>
<%= submit_tag "Search", :name => nil ,:class => 'btn' %>
<% end %>

最后,根据 twitter 引导文档,application.js 将相关的 jquery 文件。

$(function() {  
    $('.typeahead .input-medium search-query').typeahead({source:[gon.firms]});
}

我的应用程序 .js 也有以下库

//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require twitter/bootstrap
//= require_tree .

我检查了 gon.firms 是否可以作为变量使用,但开发控制台出现以下错误

uncaught syntax error: Unexpected token

任何想法可能是什么原因造成的?

有什么明显的错误吗?

【问题讨论】:

    标签: javascript jquery ruby-on-rails ruby-on-rails-3 twitter-bootstrap


    【解决方案1】:

    首先确保gon.firms 已按预期填充(检查您的网络开发工具控制台)。然后,当您在那里时,请确保您在框中键入时没有 js 错误。最后,根据the docs,您似乎想将插件附加到文本字段,而不是表单:

    $('.typeahead .search-query').typeahead( { source: gon.firms } );
    

    【讨论】:

    • 感谢您抽出宝贵的时间帮我解决这个问题,我将对此进行一次狂欢,并告诉您进展如何!
    【解决方案2】:
    这是因为 gon.firms 是 ruby​​ 数组而不是 js 数组。

    你可以把一个字符串传给js,然后像这样拆分成一个数组:

    $(function() {
        var col = "<%= @pon.firms.join(",") %>".split(",");
        $(".search-query").typeahead({ source: col });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多