如何在显示之前过滤自动完成的结果?

时间:2015-09-13 08:26:23

标签: javascript arrays filtering jquery-ui-autocomplete

我正在使用jquery-ui自动完成功能从服务器检索一些结果。我想根据客户端功能在客户端过滤结果。我怎么做?

这是我想要的伪代码:

function is_valid_value(item) {
  // returns true if item is valid, false otherwise
}

$( "#some-text-field" ).autocomplete({
      source: $.get('url/path/to/autocomplete.json?term=abc', function(data) {
          // item is an element in the data collection
          return data.filter(item) {
            return is_valid_value(item);
          }
        })
      }

我知道这不能在多个级别上工作 - 我没有传入实际的术语,而且我也遇到了语法错误 - 行{上的意外令牌return data.filter(item) { 1}}。我还查看了ajaxSuccess,它似乎主要用于提醒用户成功完成 - 我不知道它是否可用于过滤数据并将其返回。

1 个答案:

答案 0 :(得分:0)

我使用了另一种解决方案,它向服务器发送了足够的数据,以便在服务器上进行过滤:

$("#some-text-field").autocomplete({
  source: function(request, response) {
            $.ajax({
              url: '/path/to/autocomplete',
              dataType: "json",
              data: {
                term: request.term,
                blocked: blocked_results(), //a function that returns the results to block 
               },
               success: function(data) {
                 response(data);
               }
           })
});

服务器然后仅发回有效结果,因此客户端不需要过滤。