jquery – Ajax调用填充Typeahead Bootstrap

前端之家收集整理的这篇文章主要介绍了jquery – Ajax调用填充Typeahead Bootstrap前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想要做的是通过Ajax获取一个json对象,并使用一种值填充Bootstrap Typeahead.

这是我的代码

  1. nameTypeHead: function () {
  2. var _self = this,searchInput = $('#nameTypeHead'),arr = [];
  3.  
  4. function getArray() {
  5. $.ajax({
  6. url: '/Home/AutoComplete',type: 'post',dataType: 'json',data: { searchText: searchInput.val() },success: function (data) {
  7. $.each(data,function () {
  8. arr.push(this.Name);
  9. });
  10. return arr;
  11. }
  12. });
  13. }
  14.  
  15. searchInput.typeahead({
  16. source: getArray()
  17. });
  18. }

我收到arr为null的错误

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

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

我可以做什么来显示我的Json对象的值在类型中的值?

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

解决方法

我从头开始:
  1. $('#typeahead').typeahead({
  2.  
  3. source: function (query,process) {
  4. return $.getJSON(
  5. 'path/to/lookup',{ query: query },function (data) {
  6. return process(data);
  7. });
  8. }
  9.  
  10. });

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

  1. [
  2. "John","Jane","Alfredo","Giovanni","Superman"
  3. ]

如果您的数据数组具有不同的结构,只需将其重新排列,然后再传递给process()方法即可.

你可以找到一个实例here.

编辑 – 基于你的json数据:

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

getJSON回调成为:

  1. function (data) {
  2.  
  3. var newData = [];
  4.  
  5. $.each(data,function(){
  6.  
  7. newData.push(this.name);
  8.  
  9. });
  10.  
  11. return process(newData);
  12.  
  13. });

猜你在找的jQuery相关文章