我正在尝试使用 twitter bootstrap 从我的数据库中获取制造商。
因为 twitter bootstrap typeahead 不支持 ajax 调用,所以我使用这个 fork:
https://gist.github.com/1866577
在那个页面有这个comment这提到了如何做我想做的事。问题是当我运行我的代码时,我不断得到:
Uncaught TypeError: Cannot call method 'toLowerCase' of undefined
我四处搜索并尝试将我的 jquery 文件更改为使用缩小和非缩小以及托管在谷歌代码上的文件,但我一直收到同样的错误。
我的代码目前如下:
$('#manufacturer').typeahead({
source: function(typeahead, query){
$.ajax({
url: window.location.origin+"/bows/get_manufacturers.json",
type: "POST",
data: "",
dataType: "JSON",
async: false,
success: function(results){
var manufacturers = new Array;
$.map(results.data.manufacturers, function(data, item){
var group;
group = {
manufacturer_id: data.Manufacturer.id,
manufacturer: data.Manufacturer.manufacturer
};
manufacturers.push(group);
});
typeahead.process(manufacturers);
}
});
},
property: 'name',
items:11,
onselect: function (obj) {
}
});
在 url 字段上,我添加了
window.location.origin
避免已经在另一个问题上讨论过的任何问题
同样在我使用
$.each()
之前然后决定使用$.map()
正如 similar question 中推荐的 Tomislav Markovski任何人都知道为什么我一直遇到这个问题?!
谢谢
最佳答案
Typeahead 期望字符串列表作为源
$('#manufacturer').typeahead({
source : ["item 1", "item 2", "item 3", "item 4"]
})
在您的情况下,您想将它与对象列表一起使用。这样,您必须进行一些更改才能使其正常工作
这应该有效:
$('#manufacturer').typeahead({
source: function(typeahead, query){
$.ajax({
url: window.location.origin+"/bows/get_manufacturers.json",
type: "POST",
data: "",
dataType: "JSON",
async: false,
success: function(results){
var manufacturers = new Array;
$.map(results.data.manufacturers, function(data){
var group;
group = {
manufacturer_id: data.Manufacturer.id,
manufacturer: data.Manufacturer.manufacturer,
toString: function () {
return JSON.stringify(this);
},
toLowerCase: function () {
return this.manufacturer.toLowerCase();
},
indexOf: function (string) {
return String.prototype.indexOf.apply(this.manufacturer, arguments);
},
replace: function (string) {
return String.prototype.replace.apply(this.manufacturer, arguments);
}
};
manufacturers.push(group);
});
typeahead.process(manufacturers);
}
});
},
property: 'manufacturer',
items:11,
onselect: function (obj) {
var obj = JSON.parse(obj);
// You still can use the manufacturer_id here
console.log(obj.manufacturer_id);
return obj.manufacturer;
}
});
关于javascript - twitter bootstrap typeahead(未定义的方法 'toLowerCase'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11235644/