2015-11-16 6 views
1

Я пытаюсь реализовать typeahead, источником которого является API, который ожидает запроса GET с совокупностью данных, а не закодированных в url данных. Я пробовал несколько разных вещей в объекте «подготовить», но не могу заставить его кодировать параметры URL. Возможно ли это с помощью typeahead или jquery вообще, чтобы он этого не делал? У меня есть чувство jquery, возможно, просто не позволяет вам это делать, поскольку это будет считаться «плохой практикой», но изменение API на самом деле не является вариантом! Вот мой код:Как отправить данные в тело запроса при использовании Typeahead & Bloodhound?

$(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 
    }); 
}) 

Я использую JQuery 1.11.3 & typeahead.js 0.11.1.

Спасибо!

+0

'' D' на settings.DataType' должны быть в нижнем регистре '' d' настройки. dataType = "json"; '? – guest271314

+0

Спасибо за предложение! Я попробовал уменьшить dataType, но это не повлияло на поведение. – datesss

+0

Попробуйте использовать функцию substringMatcher' типа typeahead.js https://twitter.github.io/typeahead.js/examples/#file-the-basics-js, см. Сообщение – guest271314

ответ

0

Попробуйте использовать минимально измененную версию typeahead.js substringMatcher функции, .on(), input событие

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>