如何在使用Typeahead

如何在使用Typeahead

本文介绍了如何在使用Typeahead&寻血猎犬?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图实现一个typeahead,它的源代码是一个API,它需要一个带有数据体的GET请求,而不是URL编码的数据。我已经在准备对象中尝试了一些不同的东西,但无法获取到URL编码参数。一般来说,是否可以用typeahead或jquery来让它不这样做?我有一种感觉,jquery可能只是不会让你这样做,因为它被认为是'坏习惯',但改变API并不是一个真正的选择!
这是我的代码:

  $(document).ready(function(){
var people = new Bloodhound({
datumTokenizer:Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer:Bloodhound.tokenizers.whitespace,
remote:{
url:' apiUrl',
prepare:function(query,settings){
settings.type =GET;
settings.contentType =application / json;
settings.DataType = json;
settings.processData = false;
settings.data = JSON.stringify({search:people,query:query});
return settings;



$('。typeahead')。typeahead(null,{
source:people
});
$ b)

我正在使用jquery 1.11.3& typeahead.js 0.11.1。



谢谢! 试试试试使用typeahead.js的最小修改版本函数, .on(),输入事件



  var substringMatcher = function(strs,q,cb){return(function(q,cb,name){var matches,substrRegex; //一个数组将用substring匹配填充matches = []; //正则表达式用于确定一个字符串是否包含子字符串'q` substrRegex = new RegExp(q,'i'); //遍历字符串池和任何字符串//包含子字符串`q`,将它添加到`matches`数组$ .each(strs,function(i,str) {if(substrRegex.test(str)){// typeahead jQuery插件希望对JavaScript对象提供建议,请参阅typeahead文档以获取更多信息matches.push(name(str)); }}); CB(匹配); }(q,cb,function(res){return res}));}; $(#typeahead)。 gist.githubusercontent.com/guest271314/+ffac94353ab16f42160e / raw /+aaee70a3e351f6c7bc00178eabb5970a02df87e9 / states.json,processData:false,data:JSON.stringify({search:people,query:e。 (json){if(e.target.value.length){substringMatcher(JSON.parse(json),e.target.value,function(results){$(#结果ul)。empty(); $ .map(results,function(value,index){$(#results ul).append($(< li />,{class:结果 - + 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 =textid =typeaheadplaceholder =search/>< br />< div id =results> < UL> < / div>  


I'm trying to implement a typeahead whose source is an API that expects a GET request with a body of data, not url encoded data. I've tried a few different things in the 'prepare' object, but can't get it to url encode parameters. Is it possible with typeahead, or jquery in general, to have it not do this? I have a feeling jquery maybe just doesn't let you do this, since it would be considered 'bad practice', but changing the API is not really an option!Here is my code:

$(document).ready(function(){
  var people = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  remote: {
    url: 'apiUrl',
    prepare: function (query, settings) {
                      settings.type = "GET";
                      settings.contentType = "application/json";
                      settings.DataType = "json";
                      settings.processData = false;
                      settings.data = JSON.stringify({"search":"people","query":query});
                      return settings;
                   }
    }
  });
  $('.typeahead').typeahead(null, {
    source: people
  });
})

I'm using jquery 1.11.3 & typeahead.js 0.11.1.

Thanks!

解决方案

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>

这篇关于如何在使用Typeahead&amp;寻血猎犬?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:16