Twitter typeahead 0.9.3 远程返回 URL 和 JSON 对象

twitter typeahead 0.9.3 remote return URL and json object

本文关键字:返回 URL 对象 JSON typeahead 程返回 Twitter      更新时间:2023-09-26

在引导程序 2 中,我使用以下代码发布了一个 json 对象,

$('#typeahead').typeahead({
        source: function (query, process) {
         var URL = 'http://localhost:8080/autocomplete/search/';
         var query = {"t:jsonStringField": {
                          "name": "model",
                          "value": "fusion"
                         },
                      "t:jsonStringFilter": [
                             {"name": "year","value": "2009"},
                             {"name": "make","value": "ford"}
                         ]
                      }; 
            return $.getJSON(URL,
                { query: JSON.stringify(query)},
                function (data) {
                    return process(data);
                });
        }
    });

现在在推特 tyeahead 0.9.3 中,他们已经取消了源概念并转移到远程概念,但不幸的是我不知道如何使用它。

$(".typeahead").typeahead({
     remote : {    
      url: 'http://localhost:8080/autocomplete/search/',
      replace: function(uri, query) {
         var query = {"t:jsonStringField": {
                          "name": "model",
                          "value": "fusion"
                         },
                      "t:jsonStringFilter": [
                             {"name": "year","value": "2009"},
                             {"name": "make","value": "ford"}
                         ]
                      }; 
         return uri + JSON.stringify(query);
      },
      filter: function(response) {
           return response.matches;
      }
      return process(resultList);
    }
 }

不幸的是它不起作用,我如何只发布 JSON 对象而不是将其附加到字符串中?谢谢。

在原始代码中,你使用 $.getJSON。这会将请求(并期望 json 作为结果)发送到:http://localhost:8080/autocomplete/search/?query=%7B%22t%3AjsonStringField%22%3A%7B%22name%22%3A%22model%22%2C%22value%22%3A%22fusion%22%7D%2C%22t%3AjsonStringFilter%22%3A%5B%7B%22name%22%3A%22year%22%2C%22value%22%3A%222009%22%7D%2C%7B%22name%22%3A%22make%22%2C%22value%22%3A%22ford%22%7D%5D%7D

要对Twitter的Typeahead调用执行相同的操作,远程数据的替换函数应返回有效的URL。在您的函数中,缺少 url 的?query=部分。

您必须设置:网址:'http://localhost:8080/autocomplete/search/?query=',

您可能还必须对您的 json 输入进行编码。

注意:您将不需要该行return process(resultList);您必须使用过滤器函数将 json 结果转换为有效数据:

组成数据集的各个单元称为基准面。这 基准面的规范形式是具有值属性和 令牌属性。

您可以使用模板来设置下拉列表结果的样式,请参阅:http://twitter.github.io/typeahead.js/examples/

默认情况下,typeahead.js创建的下拉菜单将看起来 丑陋,你会想要设置它的样式以确保它适合主题 您的网页。

您将需要 https://github.com/jharding/typeahead.js-bootstrap.css 中的其他 CSS 来设置引导的默认下拉列表的样式。