我刚刚将后台从 Boostrap 2 迁移到 Boostrap 3。
我的预输入指令给了我一些问题。
在 bootstrap v2 上我有这个:
var typeaheadSettings = {
source: function (query, process) {
list = [];
return $.ajax({
minLength: 3,
item: 10,
url: "/ajax/articles/",
type: 'POST',
data : { query: query },
dataType: 'json',
success: function (result) {
var resultList = result.aaData.map(function (item) {
list[item.name + ' - ' + item.code + ' (' + item.category + ')'] = item.id;
return item.name + ' - ' + item.code + ' (' + item.category + ')';
});
return process(resultList);
}
});
},
updater: function (item) {
$("#parent").val(list[item]);
$(this).attr("placeholder",item);
}
};
目前,随着 Bootstrap 3 和 typeahead (v. 0.9.3) 的明确包含,我正在处理这一部分:
$(".typeahead").typeahead({
name : 'resultArticle',
remote : {
url: '/ajax/articles?query=%QUERY',
filter: function(data) {
var resultList = data.aaData.map(function (item) {
return item.name;
});
return process(resultList);
}
}
});
对json的调用是可以的,但是没有返回,我不知道我可以做什么来调试/找到解决方案。
谢谢!
最佳答案
首先您可以考虑使用 https://github.com/bassjobsen/Bootstrap-3-Typeahead .
您应该检查您的 resultList
或 process(resultList)
的结果是否具有以下格式:
The individual units that compose datasets are called datums. The canonical form of a datum is an object with a value property and a tokens property. value is the string that represents the underlying value of the datum and tokens is a collection of single-word strings that aid typeahead.js in matching datums with a given query.
为了模仿您的 /ajax/articles?query
我使用:
<?php
class names
{
var $name;
function __construct($name)
{
$this->name = $name;
}
}
$data=array();
$data['aaData'] = array();
foreach (array('kiki','dries','wolf') as $name)
{
$data['aaData'][] = new names($name);
}
echo json_encode($data);
exit;
此端点始终返回独立于查询的三个名称的列表。此列表应显示在下拉列表中。
您的(采用的)js 代码:
$(".typeahead").typeahead({
name : 'resultArticle',
remote : {
url: 'search.php?query=%QUERY',
filter: function(data) {
var resultList = data.aaData.map(function (item) {
return item.name;
});
console.log(resultList);
return resultList;
},
}
});
当我运行这个 console.log(resultList);
时,给出 ["kiki", "dries", "wolf"]
。符合数据格式的字符串数组。
预输入下拉列表也显示这些名称。 (不要忘记包含以下 CSS: https://github.com/jharding/typeahead.js-bootstrap.css https://github.com/bassjobsen/typeahead.js-bootstrap-css )
请注意,您不需要返回流程(resultList);
关于jquery - Bootstrap 3 与 Typeahead JSON 远程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18631145/