【问题标题】:typeahead js not showing resultstypeahead js不显示结果
【发布时间】:2018-01-29 13:06:24
【问题描述】:

我想使用 typeahead 远程检索邮政编码,它必须是 post,而不是 get。该调用在控制台中返回以下 json:

{suggestions: "L-6956 | IM GRUND | KEEN-SUR-DOHEEM"}
{suggestions: "L-6956 | OP DER MOUCK | KEEN-SUR-DOHEEM"}

但结果未显示在输入字段下方,以便选择其中一个结果。这是我的代码:

$('#txtPostalCode').typeahead(
  null,
  {
    name: 'txtPostalCode',
    displayKey: 'suggestions',
    minLength: 3,
    source: function (query, syncResults) {
      $.post('/hotbed/sggl/getpipedaddresses', {searchItem: query}, function (data) {
        syncResults($.map(data, function (item) {
          console.log(item.suggestions);
          return item;
        }));
      }, 'json');

    }
  });

【问题讨论】:

    标签: javascript typeahead.js


    【解决方案1】:

    根据 typeahead API,服务器响应应标记为异步,并且应使用该 asyncCB 获取您的响应,

    $('#txtPostalCode').typeahead({
      null
    },
    {
      name: 'txtPostalCode',
      displayKey: 'suggestions',
      minLength: 3,
      async: true,
      source: function (query, processSync, processAsync) {
        processSync(['This suggestion appears immediately', 'This one too']);
        return $.ajax({
          url: "/hotbed/sggl/getpipedaddresses", 
          type: 'POST',
          data: {searchItem: query},
          dataType: 'json',
          success: function (json) {
            // in this example, json is simply an array of strings
            return processAsync(json);
          }
        });
      }
    });
    

    由于这个问题有开放的赏金,我不能将其标记为重复,但您可能会在以下问题中找到更多详细信息,

    Duplicate of this question

    【讨论】:

    • 这很有帮助,但我想补充一点,当您在源函数中使用 3 个参数时,async:true 并不是强制性的。而且你不需要返回任何东西。介意我编辑吗?
    • 更快乐
    • 我已经编辑了你的答案,但审稿人并不欣赏......在它被拒绝之前接受它:(
    • 谢谢,现在它按预期工作了。但是为了完整性:在哪里可以找到 typeahead api? Ajax 为我输入的每个字符发布,如何在请求之前插入延迟?下一个问题:一旦选择了选项,我必须调用另一条路线。在哪里做这个?
    • 你可以使用 debouce 之类的东西,或者仅在 2-3 个字符后开始检查
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    相关资源
    最近更新 更多