How to send data in request body when using Typeahead & Bloodhound?

不羁岁月 提交于 2019-11-29 16:56:39

Try using minimally modified version of typeahead.js substringMatcher function , .on() , input event

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)) {
        // the typeahead jQuery plugin expects suggestions to a
        // JavaScript object, refer to typeahead docs for more info
        matches.push(name(str));
      }
    });
    cb(matches);
  }(q, cb, function(res) {
    return res
  }));
};


$("#typeahead").on("input", function(e) {
  $.ajax({
      url: "https://gist.githubusercontent.com/guest271314/"
           + "ffac94353ab16f42160e/raw/"
           + "aaee70a3e351f6c7bc00178eabb5970a02df87e9/states.json",
      processData:false,
      data: JSON.stringify({
        "search": "people",
        "query": e.target.value
      })
    })
    .then(function(json) {
      if (e.target.value.length) {
        substringMatcher(JSON.parse(json), e.target.value, function(results) {
          $("#results ul").empty();
          $.map(results, function(value, index) {
            $("#results ul")
            .append($("<li />", {
              "class": "results-" + index,
              "html": value
            }))
          })
        })
      } else {
        $("#results ul").empty();
      }
    }, function err(jqxhr, textStatus, errorThrown) {
      console.log(textStatus, errorThrown)
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" id="typeahead" placeholder="search" />
<br />
<div id="results">
  <ul>
  </ul>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!