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數組的文檔中。