Ajax调用填充引导事先键入的内容 [英] Ajax call populate Typeahead Bootstrap
问题描述
我试图做的是通过Ajax获得JSON对象并填充引导与事先键入的内容只有一个样的价值。
What I'm trying to do is to get a json object via Ajax and populate the Bootstrap Typeahead with just one kind of value.
下面是我的code:
nameTypeHead: function () {
var _self = this,
searchInput = $('#nameTypeHead'),
arr = [];
function getArray() {
$.ajax({
url: '/Home/AutoComplete',
type: 'post',
dataType: 'json',
data: { searchText: searchInput.val() },
success: function (data) {
$.each(data, function () {
arr.push(this.Name);
});
return arr;
}
});
}
searchInput.typeahead({
source: getArray()
});
}
我收到的错误改编为null
我也试过用 .parseJSON()
但没有成功:
I also tried with .parseJSON()
but with no success:
$.each($.parseJSON(data), function () {
arr.push(this.Name);
});
我能做些什么,以显示我的JSON对象在Typeahed正好值名称?
What can I do to show just the value Name of my Json Object in the Typeahed?
如果在阿贾克斯成功,我把警报(JSON.stringify(数据));
它提醒我正确的JSON对象
If in the Ajax Success I put alert(JSON.stringify(data));
it alert correctly my Json Object.
推荐答案
我从头开始做吧:
$('#typeahead').typeahead({
source: function (query, process) {
return $.getJSON(
'path/to/lookup',
{ query: query },
function (data) {
return process(data);
});
}
});
其中,数据
是一个简单的JSON数组,如:
Where data
is a simple JSON array like:
[
"John",
"Jane",
"Alfredo",
"Giovanni",
"Superman"
]
如果你的数据
阵列已经得到了不同的结构,它传递给处理()
方法之前只是重新安排
If your data
array has got a different structure, just rearrange it before passing it to process()
method.
您可以在这里找到一个活生生的例子。
You can find a live example here.
编辑 - 根据您的JSON数据:
EDIT - based on your json data:
[
{'id':'0', 'name':'John'},
{'id':'1', 'name':'Jane'},
{'id':'2', 'name':'Alfredo'},
...
}
在的getJSON
回调变为:
function (data) {
var newData = [];
$.each(data, function(){
newData.push(this.name);
});
return process(newData);
});
这篇关于Ajax调用填充引导事先键入的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!