我正试图让这个类型的人使用ajax调用,但我很接近但卡住了。
目前,它在下拉列表中返回5个“未定义”项目的列表。我已经尝试将我的ajax响应格式化为数组和json编码。
我测试了我的php资源,该资源响应了ajax调用,当我加载这个uri时:
/search?searchField=apple
在我的浏览器中使用搜索词我会得到以下格式的正确结果:
["Apple American Group","Apple Financial Holdings Inc","Apple Inc","Appleton Coated LLC","Appleton Inc","Appleton Papers Inc","Dr Pepper Snapple Group Inc","Maui Land & Pineapple Co Inc","Red Apple Group Inc"]
我可以从我的控制台输出中看到ajax调用正在被触发并成功:
XHR finished loading: GET "http://cha.dev:8000/search?searchField=a". jquery.js:9631
send jquery.js:9631
jQuery.extend.ajax jquery.js:9176
b.mixin._get typeahead.bundle.min.js:7
f
HTML:
<div class="form-group" id="bloodhound">
<input type="text" name="searchField" class="form-control typeahead" id="searchId" autocomplete="off" spellcheck="off">
</div>
<!-- just before close of body tag -->
<script src="//code.jquery.com/jquery.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="js/typeahead.bundle.min.js"></script>
<script src="js/main.js"></script>
JavaScript的:
var businesses = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: 'search?searchField=%QUERY'
});
businesses.initialize();
$('#searchId').typeahead(null, {
name: 'businessList',
displayKey: 'value',
source: businesses.ttAdapter()
});
感谢您提供任何帮助。
答案 0 :(得分:0)
键是返回的JSON的重要部分。以下示例使用business
作为键。
使用Javascript:
var businesses = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('business'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: 'search?searchField=%QUERY'
});
businesses.initialize();
$('#searchId').typeahead(null, {
name: 'businessList',
displayKey: 'business',
source: businesses.ttAdapter()
});
应返回的数据:
[ { "business": "Apple American Group"},
{ "business": "Apple Financial Holdings Inc"},
{ "business": "Apple Inc"},
{ "business": "Appleton Coated LLC"},
{ "business": "Appleton Inc"},
{ "business": "Appleton Papers Inc"},
{ "business": "Dr Pepper Snapple Group Inc"},
{ "business": "Maui Land & Pineapple Co Inc"},
{ "business": "Red Apple Group Inc"} ]