1

As of my understanding typeahead.js got three ways of fetching data.

  • Local: hardcoded data
  • Prefetch: Load a local json file, or by URL
  • Remote: Send a query to the backend which responds with matching results

I want to fetch all data from the backend and then process it on the client. The data my server responds with got the following structure:

[{id:2, courseCode:IDA530, courseName:Software Testing, university:Lund University},
{id:1, courseCode:IDA321, courseName:Computer Security, university:Uppsala University}, ...]

I want it to search on all fields in each entry. (id, courseCode, courseName, university)

I wanna do more on the client and still fetching one time for each user (instead of every time a user are typing), I probably misunderstood something here but please correct me.

4

1 回答 1

3

您应该重新阅读文档。基本上你需要两件事:

  1. 使用该prefetch:对象仅将所有数据从后端带到客户端一次(如果我理解正确,这就是您要查找的内容。)

  2. 使用filter函数将这些结果转换为基准。返回的数据可以有一个tokens字段,这将是预先搜索的内容,并且可以从您的所有数据中构建。

类似于以下内容:

$('input.twitter-search').typeahead([{
    name: 'courses',
    prefetch: {
        url: '/url-path-to-server-ajax-that-returns-data',
        filter: function(data) {
            retval = [];
            for (var i = 0;  i < data.length;  i++) {
                retval.push({
                    value: data[i].courseCode,
                    tokens: [data[i].courseCode, data[i].courseName, data[i].university],
                    courseCode: data[i].courseCode,
                    courseName: data[i].courseName,
                    template: '<p>{{courseCode}} - {{courseName}}</p>',
                });
            }
            return retval;
        }
    }
}]);
于 2013-09-21T16:33:03.883 回答