$('.typeahead').typeahead({
ajax: {
url: './test.php',
triggerLength: 1
}
});
test.php返回json:
[{"id":"13","name":"\u0410\u0420\u0425\u0418\u0412"},
{"id":"12","name":"\u041a\u043e\u043f\u0438\u0440\u0430\u0439\u0442\u0435\u0440"},
{"id":"11","name":"\u041f\u043e\u043c\u043e\u0449\u043d\u0438\u043a \u043c\u0435\u043d\u0435\u0434\u0436\u0435\u0440\u0430"}]
请告诉我,当我们选择值typeahead时,我是如何在console.log()
或alert()
元素id
中从json输出的?
P.S。:或只是如何从json获得id
?
答案 0 :(得分:0)
将此分配给某个变量,然后使用index get元素,然后使用其字段ID:
var a = [{"id":"13","name":"\u0410\u0420\u0425\u0418\u0412"}, {"id":"12","name":"\u041a\u043e\u043f\u0438\u0440\u0430\u0439\u0442\u0435\u0440"},
{"id":"11","name":"\u041f\u043e\u043c\u043e\u0449\u043d\u0438\u043a \u043c\u0435\u043d\u0435\u0434\u0436\u0435\u0440\u0430"}]
然后你得到:
a[0].id = 13
答案 1 :(得分:0)
$('.typeahead').typeahead({
ajax: {
url: './test.php',
triggerLength: 1
},
onSelect: function(item) {
console.log(item); // return full object
console.log(item.value); // return value - it your id
return item;
}
});
答案 2 :(得分:0)
这是使用Typeahead的常用方法(我所做项目的100%工作代码):
var films = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.value); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: './test.php'
});
films.initialize();
$('.typeahead').typeahead(null, {
displayKey: 'value',
source: films.ttAdapter(),
templates: {
suggestion: Handlebars.compile('<p>{{value}} ({{year}}) <span class="label label-elegant">{{videoRes width height}}</span></p>')
}
});
它使用Handlebars进行模板化和Bloodhound作为建议引擎 https://github.com/twitter/typeahead.js/blob/master/doc/bloodhound.md
现在,正如您所说,您需要生成console.log
收到的数据,以下是示例代码:
var films = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.value); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: './test.php'
});
films.initialize();
var autocomplete_template = Handlebars.compile('<p>{{value}} ({{year}}) <span class="label label-elegant">{{videoRes width height}}</span></p>');;
function suggestions_html(x){
// Log function
console.log(JSON.stringify(x));
return autocomplete_template(x);
}
$('.typeahead').typeahead(null, {
displayKey: 'value',
source: films.ttAdapter(),
templates: {
suggestion: suggestions_html
}
});