jQuery Ajax 调用填充 Typeahead Bootstrap

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12621823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:52:54  来源:igfitidea点击:

Ajax call populate Typeahead Bootstrap

jqueryajaxjsontwitter-bootstrap

提问by Ayeye Brazo

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.

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

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

I receive the error that arr is null

我收到arr 为空的错误

I also tried with .parseJSON()but with no success:

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

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

What can I do to show just the value Name of my Json Object in the Typeahed?

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

If in the Ajax Success I put alert(JSON.stringify(data));it alert correctly my Json Object.

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

回答by moonwave99

I made it from scratch:

我从头开始制作:

$('#typeahead').typeahead({

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

});

Where datais a simple JSON array like:

data一个简单的 JSON 数组在哪里,如:

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

If your dataarray has got a different structure, just rearrange it before passing it to process()method.

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

You can find a live example here.

你可以在这里找到一个活生生的例子。

EDIT - based on your json data:

编辑 - 基于您的 json 数据:

[
    {'id':'0', 'name':'John'},
    {'id':'1', 'name':'Jane'}, 
    {'id':'2', 'name':'Alfredo'},
    ...
}

The getJSONcallback becomes:

getJSON回调变为:

function (data) {

    var newData = [];

    $.each(data, function(){

        newData.push(this.name);

    });

    return process(newData);

}); 

回答by mc.

Checkout this gist. Does autocomplete, deals with fast typers, and caches

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

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

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

回答by Akash

This is what worked for me:-

这对我有用:-

HTML Setup :

HTML 设置:

<!-- HTML Setup-->
<input type="text" id="my-typeahead" />

Javascript :

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 '<div>' + user.name + '</div>';
        },
        pending: '<div>Please wait...</div>'
    }
});

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

References:

参考:

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

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

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

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

Good Luck.

祝你好运。