使用typeahead.js使用XML文件填充列表

时间:2016-07-01 15:33:09

标签: javascript xml

我实际上并不知道从哪里开始,因为文档并没有真正解释过。

我想使用我在网站上加载的外部XML文件生成自动填充列表。

到目前为止,我已将此应用于输入字段:

$('.typeahead').typeahead({
    highlight: true
},
{
    name: 'brands',
    display: 'value',
    source: function(query, syncResults, asyncResults) {
        $.get('/?s=' + query, function(data) {
            asyncResults(data);
        });
    }
});

搜索后,我会看到搜索查询的每个字母都会显示额外的GET请求。但是在控制台中我看到以下错误:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in <!DOC - jquery.js?ver=1.12.4:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in <!DOC

不太清楚这意味着什么:S

我想将http://services.inveroak.co.uk/readerimages/livepanel/91112.xml设置为要读取的源XML文件,然后在输入条目时显示XML中的各种值。然后我想在单击这些条目时跳转到URL

我是否使用合适的工具进行工作?

1 个答案:

答案 0 :(得分:0)

您可以使用$.get()$.map()input事件,typeahead.js substringMatcher功能的修改版

$(function() {
  var source; // source `.xml`
  var substringMatcher = function(strs, q, cb) {
    return (function(q, cb, name) {
      var matches, substrRegex;

      // an array that will be populated with substring matches
      matches = [];

      // regex used to determine if a string contains the substring `q`
      substrRegex = new RegExp(q, 'i');

      // iterate through the pool of strings and for any string that
      // contains the substring `q`, add it to the `matches` array
      $.each(strs, function(i, str) {
        if (substrRegex.test(str)) {

          matches.push(name(str));
        }
      });

      cb(matches);
    }(q, cb, function(res) {
      return res
    }));
  };
  $.get("data.xml") // get `xml` source
    .then(function(xml) {
      // define `source` as array containing `.textContent`
      // of `Name` elements
      source = $.map($(xml).find("Name"), function(node) {
        return node.textContent 
      });
      return source
    })
    .then(function(src) {   
      // `source` is defined, use `input` event to 
      // pass current `input` value to `substringMatcher` function
      $(".typeahead").on("input", function(e) {   
        substringMatcher(src, e.target.value, function(results) {
          // display results
          $("#results ul").empty();
          $.map(results, function(value, index) {
            $("#results ul")
              .append($("<li />", {
                "class": "results-" + index,
                "html": value
              }))
          })
        })
      });
    })
});

plnkr http://plnkr.co/edit/VsHft9g74XczO1yrSJW7?p=preview

相关问题