Jquery ui automplete + json,无法在列表中显示“无结果”

时间:2017-03-11 05:41:06

标签: jquery jquery-ui autocomplete jquery-ui-autocomplete

我尝试自动完成,但面临一个问题 - 我无法显示“没有找到结果”。有两个问题:它显示“无结果”5次或没有显示任何内容。代码如下:

$(document).ready(function() {
$( "#cities" ).autocomplete({
  source: function(request, response){
    var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
    $.ajax({
      url: "cities.json",
      crossDomain: true,
      dataType: "json",
      success: function(data){
       response($.map(data, function(v,i){
            var text = v.City;
            if(text && ( !request.term || matcher.test(text))){
                return {
                    label: v.Id,
                    value: v.City
                };
            }else{  
                  value: "No result"
            }
        }));
      }
    });
  },
  minLength: 1,
  autoFocus: true
  });
});

我使用了本地json文件,其中包含以下数据:

[
{
"Id": 0,
"City": "Toronto"
},{
"Id": 1,
"City": "New-York" 
},{
"Id": 2,
"City": "Moscow"
},{
"Id": 3,
"City": "Monreal" 
},{
"Id": 4,
"City": "Vancouver"
},{
"Id": 5,
"City": "Williamsburg" 
}
]

1 个答案:

答案 0 :(得分:0)

返回"没有结果"您必须将[ "No Results" ]数组传递给response回调。

$(document).ready(function() {
  $( "#cities" ).autocomplete({
    source: function(request, response){
      var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i" );
      $.ajax({
        url: "cities.json",
        crossDomain: true,
        dataType: "json",
        success: function(data){
          var results = [];
          $.each(data, function(k,v){
            var text = v.City;
            if(text && (!request.term || matcher.test(text))){
              results.push({
                label: v.Id,
                value: v.City
              });
            }
          });
          if(results.length == 0){
            results.push({ label: "No Results", value: null });
          }
          response(results);
        }
      });
    });
  },
  minLength: 1,
  autoFocus: true
  });
});