使用JSON的Twitter Bootstrap自动完成器

时间:2012-09-16 16:36:41

标签: spring-mvc twitter-bootstrap

我一直在尝试使用Spring MVC带注释的控制器来使用Twitter Bootstrap自动完成程序。

我有以下HTML:

<div class="control-group">
            <label class="control-label" for="name">Supplier</label>
            <div class="controls">
                <input id="supplier" name="supplier" class="input-xlarge" data-provide="typeahead" type="text"/>    
            </div>
        </div>

以及以下javascript:

<script src="/resources/js/jquery.js"></script>
    <script src="/resources/js/bootstrap.js"></script>
    <script type="text/javascript">

    $('#supplier').typeahead({
        source: function (query, process) {
            return $.get('http://localhost:8080/supplier/search', { query: query }, function (data) {
                return process(data);
            });
        },

        minLength : 3,
        items : 4,
        property: 'name'
    });
    </script>

当一个类型三个字母我看到正确的请求到我的控制器,它返回一个供应商对象作为JSON:

{"supplier":{"name":"test","id":0,"version":0,"url":null}}

但是,文本字段未显示返回的供应商。任何人都可以提供任何帮助,说明为什么这不起作用?

2 个答案:

答案 0 :(得分:2)

process()需要一个字符串数组,而不是对象数组。因此,不是传递一个对象,而是传递一个数组,其中包含您要在文本字段中显示的内容,即[ "test" ]

另外,作为建议,要将typeahead与远程来源一起使用,我建议您使用此plugin。除此之外,它允许您使用对象数组而不是字符串数组。

答案 1 :(得分:1)

$('#supplier').typeahead({
        source: function (query, process) {
            return $.get('http://localhost:8080/supplier/search', { query: query }, function (data) {
                return process(data);
            });
        },
Replace the above code to the below one

$('#supplier').typeahead({
    source: function(typeahead, query) {
        $.ajax({
            url: "http://localhost:8080/supplier/search')?>",
            dataType: "json",
            type: "POST",
            data: {
                max_rows: 15,
                search_key: query,
                ajax: 1
            },
            success: function(data) {
                var return_list = [], i = data.length;
                while (i--) {
                    return_list[i] = {Name: data[i].Name, value: data[i].Name'};
                }
                typeahead.process(return_list);
            }
        });
    },
    onselect: function(obj) {
        $('[name="name"]').val(obj.id);
    }
});