【问题标题】:Trouble implementing a custom source with typeahead.js使用 typeahead.js 实现自定义源时遇到问题
【发布时间】:2014-02-14 15:07:28
【问题描述】:

我正在尝试将自定义源(远程)与 typeahead.js 一起使用,但在让事情正常工作时遇到了一些麻烦。如果我对数据进行硬编码,一切正常,但是当我尝试实现对远程服务的调用时,永远不会调用该调用,因此永远不会检索数据来填充预先输入的内容。

代码如下:

var places = function(query, cb){
    $.getJSON({
        url: "https://api.foursquare.com/v2/venues/search?v=20120321&intent=global&query=%QUERY&client_id="+App.fs.client_id+"&client_secret="+App.fs.client_secret,        
        success: function(results){
            cb(results.response.venues);
        },
        error: function(){
             console.log("error");
        }
    });
};

$("#search").typeahead({
        highlight: true
    },
    {
        name: "Places",
        displayKey: "name",
        source: places
    }
);

如果我创建一个名为 results 的对象并手动构造数据并将其传递给 cb,则一切正常。然而,通过这个实现,$.getJSON 甚至不会被调用。我错过了什么?

谢谢!

【问题讨论】:

  • 我猜链接不能正常工作。您是否尝试过手动检查链接是否返回 JSON 数据?

标签: javascript typeahead.js


【解决方案1】:

事实证明,问题在于我如何实现$.getJSON。我认为该函数的签名是选项的哈希值,但事实并非如此,它实际上是(url, [data], [success])。将其更改为正确的签名可以使事情正常进行。

感谢所有快速回复!

【讨论】:

    【解决方案2】:

    我认为你可以这样做

    var search = $("#search").typeahead({
        highlight: true,
        source: []
    };
    

    现在您可以使用异步请求从服务器获取数据

    $.getJSON({
        url: "https://api.foursquare.com/v2/venues/search?v=20120321&intent=global&query=%QUERY&client_id="+App.fs.client_id+"&client_secret="+App.fs.client_secret,        
        success: function(results){
            // some logic to filter, process results from server
            // now you can directly update typeahead source
            search.data('typeahead').source = results; 
        },
        error: function(){
             console.log("error");
        }
    });
    

    另请阅读thisthis discussion

    我也喜欢 selectize.js 库,它有丰富的 api,try it

    【讨论】:

      【解决方案3】:

      请注意,使用 typeahead.js,您不必手动加载数据。使用预取 URL 将在页面加载时抓取数据,然后存储在 localStorage 中

      $('#input').typeahead([
      {
          name: 'places',
          prefetch: four_square_url_query,
      }
      ]);
      

      您的示例中的“地点”不是一个函数吗?怎么样:

      var places;
       $.getJSON({
              url: fsquare_query,        
              success: function(results){
                  places = results.response.venues;
              },
              error: function(){
                   console.log("error");
              }
          });
      

      我相信最近的预输入没有“来源”属性,而是有“本地”属性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-16
        • 1970-01-01
        • 2011-10-28
        • 2012-04-01
        • 1970-01-01
        • 2016-04-12
        相关资源
        最近更新 更多