在打字头上获取ID和名称

时间:2019-05-16 01:11:18

标签: javascript ajax typehead

我可以返回名称和ID,但我只能打印名称。

我已经尝试过更新和精巧

此刻,我已经有了这段代码并且可以正常工作,但是我只知道名字了!

 $('input.typeahead').typeahead({
    source:  function (query, process) {
    return $.ajax({
    url: "search/autocomplete",
    type: "GET",
    data: "query=" + query,
    success: function(data) {

      var data = $.merge( $.merge( [], data['2'] ), data['1'] );
      return process(data); 
    }
    });

   }         
 });

得到的结果是获得的名称和ID(ID应打印在其他div上,例如#mydiv

谢谢!

2 个答案:

答案 0 :(得分:0)

答案仅在选择后添加

  $('input.typeahead').typeahead({
   source:  function (query, process) {
     return $.ajax({
     url: "search/autocomplete",
     type: "GET",
     data: "query=" + query,
     success: function(data) {

    var data = $.merge( $.merge( [], data['2'] ), data['1'] );

    return process(data); 

         // this returns an array checked with console
  }

});

},
 afterSelect: function(data){
    console.log(data.id);
}
 });

答案 1 :(得分:0)

您可以为带有猎犬的排字机指令

app.directive('typeheadDirective', function() {
    return {
        restrict: 'A',
        scope: {
            themes: '=',
            output: '=',
        },
        link: function(scope, element, attrs) {
            var themes = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.obj.whitespace('theme_name'),
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                local: scope.themes,
            })
            element.typeahead(null, {
                name: 'themes',
                displayKey: function(item) {
                    return item.theme_name
                },
                source: themes.ttAdapter()
            })
            element.bind('typeahead:select', function(ev, theme) {
                scope.output = {
                    'id': theme.id,
                    /*'theme_id': theme.id,*/
                    'theme_name': theme.theme_name
                }
                // element.value = ''
                scope.$apply();
            })
        }
    };
});