2013-05-15 21 views
4

我正在使用typeahead.js。我正在使用預取選項,需要解析返回的數據。這不是拋出一個錯誤;它沒有做任何事情。我查找了一些例子,但沒有一個使用Prefetch Filter選項。使用typeahead.js預取過濾器(使用基本選項)

Link to the prefetch documentation

我的代碼(即不工作,但不引發錯誤):

$('#autocomplete').typeahead('destroy').typeahead({         
    name: 'organizations', 
    prefetch: { 
     url: 'jsoncall', 
     filter: function() { 
         // Blatant hardcoded return value 
         return ['test-a','test-b','test'c]; 
         } 
     } 
    } 
); 

我的HTML:

<input id="autocomplete" class="large-12" autocomplete="off" type="text" placeholder="Enter school name"> 

我的困惑:

0________0 
+0

這有助於。 ..http://stackoverflow.com/questions/16321544/twitters-bootstrap-typeahead-setup –

+0

我喜歡幽默 – Meredith

回答

6

你可以通過了通過filter函數返回數據,然後根據您的喜好解析數據。因此,在你上面的例子,你會做這樣的事情:

$('#autocomplete').typeahead({         
    name: 'organizations', 
    prefetch: 
      { 
     url: 'jsoncall', 
     filter: function(data){ 
       // filter the returned data 
       return [data.movies[0].title, data.movies[1].title, data.movies[2].title]; 
     } 
    } 
} 
); 

上面的例子會工作,如果你返回的數據集是看起來是這樣的一個JSON對象:

movies: [{id:12865, title:Kill Bill: Volume 1, year:2003, mpaa_rating:R, runtime:111,…},…] 
0: {id:12865, title:Kill Bill: Volume 1, year:2003, mpaa_rating:R, runtime:111,…} 
1: {id:12862, title:Kill Bill, Volume 2, year:2004, mpaa_rating:R, runtime:137,…} 
2: {id:771237417, title:Kill Bill: The Whole Bloody Affair, year:2011,  mpaa_rating:Unrated, runtime:,…} 
3: {id:770998578, title:Angel of Death: Killer Nurse: A Bill Kurtis Special Report, year:2006,…} 
4: {id:771352617, title:Kedi Billa Killadi Ranga, year:2013, mpaa_rating:Unrated, runtime:145,…} 
total: 5 
+0

對不起延遲接受。謝謝。 –