laravel - Typeahead |输入字段将填充JSON数据而不是建议

时间:2017-04-13 16:57:23

标签: javascript jquery json typeahead.js laravel-5.4

我正在尝试在我的laravel 5.4项目中实现搜索功能  我正面临一个问题,建议在下拉列表中显示正常,但当我选择其中任何一个时,输入字段将填充json数据而不是建议字符串。

这是view和jquery:

<div class="input-group input-medium " style="float: right; padding-top: 3px; ">
    <input type="search" name="q" class="form-control search-input" placeholder="search customer" autocomplete="off" >    
</div>

<script>
    jQuery(document).ready(function($) {
        // Set the Options for "Bloodhound" suggestion engine
        var engine = new Bloodhound({
            remote: {
                url: '/find_customer?q=%QUERY%',
                wildcard: '%QUERY%'
            },
            datumTokenizer: Bloodhound.tokenizers.whitespace('q'),
            queryTokenizer: Bloodhound.tokenizers.whitespace
        });

        $(".search-input").typeahead({
            hint: true,
            highlight: true,
            minLength: 1
        }, {
            source: engine.ttAdapter(),

            // This will be appended to "tt-dataset-" to form the class name of the suggestion menu.
            name: 'usersList',

            // the key from the array we want to display (name,id,email,etc...)
            templates: {
                empty: [                      

                    '<a class="list-group-item">Nothing found.</a>'
                ],
                header: [
                    '<div class="input-group input-results-dropdown">'
                ],
                suggestion: function (data) {

                            return '<a class="list-group-item">'  + data.first_name + ' ' +data.last_name + '</a>'



          }
            }
        });
    });
</script>

请帮忙

1 个答案:

答案 0 :(得分:0)

参考docs

display - 对于给定的建议,确定它的字符串表示形式。在选择建议后设置输入控件的值时将使用此选项。可以是键字符串,也可以是将建议对象转换为字符串的函数。默认为字符串化建议。

$(".search-input").typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    }, {
        source: engine.ttAdapter(),

        // This will be appended to "tt-dataset-" to form the class name of the suggestion menu.
        name: 'usersList',
        display: 'ID' // insert values to show here

        // the key from the array we want to display (name,id,email,etc...)
        templates: {
            empty: [                      

                '<a class="list-group-item">Nothing found.</a>'
            ],
            header: [
                '<div class="input-group input-results-dropdown">'
            ],
            suggestion: function (data) {

                        return '<a class="list-group-item">'  + data.first_name + ' ' +data.last_name + '</a>'



      }
        }
    });