使用带有typeahead.js的预取过滤器(使用基本选项)

时间:2013-05-15 17:48:05

标签: javascript jquery autocomplete typeahead.js

我正在使用typeahead.js。我正在使用预取选项,需要解析返回的数据。这不是一个错误;它没有做太多的事情。我查找了示例,但没有一个使用Prefetch Filter选项。

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

1 个答案:

答案 0 :(得分: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