Bootstrap typeahead ajax result format - Example

前端 未结 2 1325
独厮守ぢ
独厮守ぢ 2020-12-23 18:27

I am using Bootstrap typeahead with an ajax function, and want to know what is the correct Json result format, to return an Id and a descripcion. I need the Id to bind the t

2条回答
  •  醉话见心
    2020-12-23 18:56

    I try for two days and finally I could it working. Bootstrap Typeahead doesn't support an array of objects as a result by default, only an array of string. Because "matcher", "sorter", "updater" and "highlighter" functions expect strings as parameter.

    Instead, "Bootstrap" supports customizable "matcher", "sorter", "updater" and "highlighter" functions. So we can rewrite those functions in Typeahead options.

    II used Json format, and bound the Id to a hidden html input.

    The code:

    $('#myTypeahead').typeahead({
        source: function (query, process) {
            return $.ajax({
                url: $('#myTypeahead').data('link'),
                type: 'post',
                data: { query: query },
                dataType: 'json',
                success: function (result) {
    
                    var resultList = result.map(function (item) {
                        var aItem = { id: item.Id, name: item.Name };
                        return JSON.stringify(aItem);
                    });
    
                    return process(resultList);
    
                }
            });
        },
    
    matcher: function (obj) {
            var item = JSON.parse(obj);
            return ~item.name.toLowerCase().indexOf(this.query.toLowerCase())
        },
    
        sorter: function (items) {          
           var beginswith = [], caseSensitive = [], caseInsensitive = [], item;
            while (aItem = items.shift()) {
                var item = JSON.parse(aItem);
                if (!item.name.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(JSON.stringify(item));
                else if (~item.name.indexOf(this.query)) caseSensitive.push(JSON.stringify(item));
                else caseInsensitive.push(JSON.stringify(item));
            }
    
            return beginswith.concat(caseSensitive, caseInsensitive)
    
        },
    
    
        highlighter: function (obj) {
            var item = JSON.parse(obj);
            var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
            return item.name.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
                return '' + match + ''
            })
        },
    
        updater: function (obj) {
            var item = JSON.parse(obj);
            $('#IdControl').attr('value', item.id);
            return item.name;
        }
    });
    

提交回复
热议问题