Ajax调用填充Typeahead Bootstrap

我想要做的是通过Ajax获取一个json对象,并使用一种值填充Bootstrap Typeahead。

这是我的代码:

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() }); } 

我收到arr为null的错误

我也试过.parseJSON()但没有成功:

 $.each($.parseJSON(data), function () { arr.push(this.Name); }); 

我该怎么做才能在Typeahed中显示我的Json对象的值Name?

如果在Ajax Success中我放了alert(JSON.stringify(data)); 它正确地警告我的Json对象。

我是从头开始做的:

 $('#typeahead').typeahead({ source: function (query, process) { return $.getJSON( 'path/to/lookup', { query: query }, function (data) { return process(data); }); } }); 

data是一个简单的JSON数组,如:

  [ "John", "Jane", "Alfredo", "Giovanni", "Superman" ] 

如果您的data数组具有不同的结构,只需在将其传递给process()方法之前重新排列它。

你可以在这里找到一个实例。

编辑 – 基于您的json数据:

 [ {'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); }); 

查看这个要点。 自动完成,处理快速打字机和缓存

https://gist.github.com/mrgcohen/5062352

这对我有用: –

HTML设置:

   

Javascript:

 /* example remote-data-source [ { id:1, name:'Batman' },{ id:2, name:'Superman' } ] */ $('#my-typeahead').typeahead({ hint: true, highlight: true, minLength: 1 }, { name: 'myDataset', source: function(str, sync, async) { // abstracting out the "REST call and processing" in a seperate function restCall(str, async); }, templates: { suggestion: function(user) { return '
' + user.name + '
'; }, pending: '
Please wait...
' } }); // The function that will make the REST call and return the data function restCall(str, async) { return $.ajax('http://url-for-remote-data-source/query?name=' + str, { // headers and other setting you wish to set-up headers: { 'Content-Type': 'application/json', }, // response success: function(res) { //processing data on response with 'async' return async(res.data); } }); }

参考文献:

Typeahead Docs - Datasets : https : //github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#datasets

Jquery **$.ajax()** : https : //api.jquery.com/jquery.ajax/

祝好运。