【问题标题】:Ajax call populate Typeahead BootstrapAjax 调用填充 Typeahead Bootstrap
【发布时间】:2012-09-19 06:21:45
【问题描述】:

我要做的是通过 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 对象的值名称?

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

【问题讨论】:

  • success 回调不必返回任何内容,因为它是一个异步调用 - 检查 this example instead
  • 另外,如果我删除return arr;,它也不起作用...
  • 从你的链接我无法理解 CoffeeScript。我应该在哪里声明property: "name"

标签: jquery ajax json twitter-bootstrap


【解决方案1】:

我是从零开始的:

$('#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() 方法之前重新排列即可。

你可以找到一个活生生的例子here

编辑 - 基于您的 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);

}); 

【讨论】:

  • 只有一个问题,为什么我要在url中添加+query ?!?
  • 我的控制台日志说:TypeError: typeahead.process is not a function
  • 好吧,您正在根据您输入的内容向服务器询问内容 - query 字符串。
  • 我使用data: { ... : ... }传递值
  • 很好的答案。但是你应该写process(data); return; 而不是return process(data);
【解决方案2】:

查看此要点。是否自动完成、处理快速类型和​​缓存

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

【讨论】:

  • 这应该是公认的答案。更加复杂和高效。谢谢你的要点!
  • 为此想出了我自己的解决方案,但效果不是很好,我对此很不满意。这个很好很简单。 -- 请注意其他人,您的大麦需要添加或执行任何操作,只需复制代码,更改您的getJSON 的 URL。开箱即用。
  • 谢谢你喜欢它。它也有一些很好的要点。
【解决方案3】:

这对我有用:-

HTML 设置:

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

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

参考资料:

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

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

祝你好运。

【讨论】:

  • 这可行,但请确保您的特定 ajax 调用成功响应中 res 变量的格式。
猜你喜欢
  • 2013-02-04
  • 1970-01-01
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多