js 通过elasticsearch实现页面输入自动补全


比较优秀的一个Autocomplete框架看一下
使用很简单,3步走

页面input元素id设置一下,比如id=autocomplete,然后页面上引用相关的js及css文件

 <input type="search" name="search-field" id="autocomplete" placeholder="Search Blog" required="">

js中定义Autocomplete的数据来源及行为配置

    // Initialize autocomplete with ajax service
    $('#autocomplete').devbridgeAutocomplete({
        serviceUrl: '/html/ncl-search',
        minChars: 1,
        onSelect: function (suggestion) {
            $('#selection').html('You selected: ' + suggestion.value + ', ' + suggestion.data.category);
        },
        showNoSuggestionNotice: true,
        noSuggestionNotice: 'Sorry, no matching results',
        maxHeight: '600',
        groupBy: 'category'
    });

后台数据源与elasticsearch连接,能为serviceUrl/html/ncl-search的调用返回正确的数据格式

需要注意返回的数据格式有以下两种,如果格式错误的话页面是无法显示正确效果的

不需要group显示效果的

{
  "query": "Unit",
  "suggestions": [
    {
      "value": "United Arab Emirates",
      "data":  "NBA"
    },
    {
      "value": "United Kingdom",
      "data": "NBA"
    },
    {
      "value": "United States",
      "data":"NBA"
    }
  ]
}

有group显示效果的,就是本篇调用中所使用的数据格式

{
  "query": "Unit",
  "suggestions": [
    {
      "value": "United Arab Emirates",
      "data":  { "category": "NBA" }
    },
    {
      "value": "United Kingdom",
      "data":  { "category": "NBA" }
    },
    {
      "value": "United States",
      "data": { "category": "NBA" }
    }
  ]
}

声明:梨木乔の技术栈|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - js 通过elasticsearch实现页面输入自动补全


梨木乔の技术栈