0

我使用Twitter Bootstrap和typeahead。Twitter引导-typeahead

我下载插件:Twitter的引导插件事先键入的内容扩展

等长这么好,它的工作时,我使用的是静态的JavaScript JSON数组如。

$('#demo1').typeahead({ 
     source: [ 
      { id: 9000, name: 'Aalborg' }, 
      { id: 2, name: 'Montreal' }, 
      { id: 3, name: 'New York' }, 
      { id: 4, name: 'Buffalo' }, 
      { id: 5, name: 'Boston' }, 
      { id: 6, name: 'Columbus' }, 
      { id: 7, name: 'Dallas' }, 
      { id: 8, name: 'Vancouver' }, 
      { id: 9, name: 'Seattle' }, 
      { id: 10, name: 'Los Angeles' } 
     ], 
     itemSelected: displayResult 
    }); 

当我尝试使用AJAX它会做enerything,我的代码看起来是这样。

$('.typeahead').typeahead({ 
      ajax: '/actions/search/synonymSearch', 
      itemSelected: displayResult 
     }); 

和返回该JSON数组(我可以在所有的方式重建其,我不能让它的工作)

[ 
    { id: 1, name: 'Toronto' }, 
    { id: 2, name: 'Montreal' }, 
    { id: 3, name: 'New York' }, 
    { id: 4, name: 'Buffalo' }, 
    { id: 5, name: 'Boston' }, 
    { id: 6, name: 'Columbus' }, 
    { id: 7, name: 'Dallas' }, 
    { id: 8, name: 'Vancouver' }, 
    { id: 9, name: 'Seattle' }, 
    { id: 10, name: 'Los Angeles' } 
] 

插件主页。 https://github.com/tcrosen/twitter-bootstrap-typeahead

我HOBE enybardy可以帮助我在这里:)

非常感谢所有帮助,:)

编辑 - 问题resovle! :) 只需要将header("content-type: application/json"); 添加到我的PHP文件中,hobe这个答案对于其他人来说是有用的! :)

+0

我真的不明白你在做什么。但是关于用户选择什么东西的部分,因为它会变成一个邮政编码 - 这是您需要实现的功能,而不是键入控件的一部分。 –

+0

我会尽力解释,所以,:) – ParisNakitaKejser

回答

0

我不认为typeahead可以读取数组的source,因此我会先解析它。

var data = [{"id":"9000","name":"Aalborg"},{"id":"9220","name":null},{"id":"9210","name":null},{"id":"9200","name":"Aalborg SV"}]; 

// using underscore.js get an array of the city names 
var cities = _.pluck(data, "name"); 

// now start typeahead 
$el.typeahead(
    source: cities, 
    // the value of the `city` selected gets passed to the onselect 
    onselect: function(city) { 
     // get the index of city selected from the data array 
     var i = _.indexOf(data, city); 
     // then using the index get what ever other value you need from the array 
     // and insert in the DOM etc.. 

    } 
); 
+0

如果你阅读我的问题,我会希望你了解它^^现在我使用一个新的插件引导和hobe你仍然可以帮助我。 – ParisNakitaKejser

0

您遇到的这个问题可能是由于您通过ajax调用的页面没有返回正确的标题。

如果您正在使用PHP,请尝试将header('Content-type: application/json');添加到包含JSON数组的文档中。