Ajax调用填充Typeahead Bootstrap

Aye*_*azo 16 ajax jquery json twitter-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()
        });
    } 
Run Code Online (Sandbox Code Playgroud)

我收到arr为null的错误

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

$.each($.parseJSON(data), function () {
   arr.push(this.Name);
});
Run Code Online (Sandbox Code Playgroud)

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

如果在Ajax Success中我alert(JSON.stringify(data));正确地提醒我的Json对象.

moo*_*e99 33

我是从头开始做的:

$('#typeahead').typeahead({

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

});
Run Code Online (Sandbox Code Playgroud)

data简单的JSON数组在哪里:

 [
   "John",
   "Jane",
   "Alfredo",
   "Giovanni",
   "Superman"
 ]
Run Code Online (Sandbox Code Playgroud)

如果你的data数组有不同的结构,只需重新排列它然后再传递给process()方法.

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

编辑 - 基于您的json数据:

[
    {'id':'0', 'name':'John'},
    {'id':'1', 'name':'Jane'}, 
    {'id':'2', 'name':'Alfredo'},
    ...
}
Run Code Online (Sandbox Code Playgroud)

getJSON回调变为:

function (data) {

    var newData = [];

    $.each(data, function(){

        newData.push(this.name);

    });

    return process(newData);

}); 
Run Code Online (Sandbox Code Playgroud)


mc.*_*mc. 7

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

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