2012-02-22 65 views
2

语境

  • 我使用jQuery UI自动完成与远程数据源。
  • 信息来源以这种格式发送数据:[{'label':'Bob', 'id':'03362548'}, {...}]
  • 我在搜索开始时显示一个加载器gif。
  • 数据过滤在服务器端完成。
  • 如果没有结果,我想隐藏加载程序gif(服务器发送[])。

问题

如何检测如果搜索没有结果隐藏装载机GIF?自动完成:检测没有结果与远程数据源

代码

$('#redir-output').autocomplete({ 
    source: 'php/ajax/autocomplete.php', 
    search: function(event, ui) { 
     $('#redir-loader').show(); 
    }, 
    open: function(event, ui) { 
     $('#redir-loader').hide(); 
    }, 
    select: function(event, ui) { 
     $(this).attr('name', ui.item.id); 
    } 
}); 

回答

1

默认情况下,当插件显示的结果,它会检查是否存在的数据显示。如果没有,则关闭菜单。

_response: function(content) { 
    if (!this.options.disabled && content && content.length) { 
     ... 
    } else { 
     // it closes the menu when content.length == 0 (no data) 
     this.close(); 
    }​ 

关闭菜单引发了“关闭”事件,所以我尽管你可以使用它。然而,这只是触发关闭事件时,菜单可见:

close: function(event) { 
    clearTimeout(this.closing); 
    // as the menu might not be visible at that moment, this is reliable 
    if (this.menu.element.is(":visible")) { 
     ... 
     this._trigger("close", event); 
    } 
}​ 

我认为你将不得不使用源作为回调并实现自己的Ajax请求。使用“完整”回调,您可以隐藏加载图标,在请求结束时,无论如何都应该隐藏,数据返回与否:

$('#redir-output').autocomplete({ 
    source: function(request, response) { 

     $.ajax({ 
      url: 'php/ajax/autocomplete.php', 
      data: request, 
      dataType: "json", 
      success: function(data, status) { 
       response(data); 
      }, 
      error: function() { 
       response([]); 
      }, 
      complete: function() { 
       $('#redir-loader').hide(); 
      } 
     }); 

    }, 

    , 
    search: function(event, ui) { 
     $('#redir-loader').show(); 
    }, 
    open: function(event, ui) { 
     $('#redir-loader').hide(); 
    }, 
    select: function(event, ui) { 
     $(this).attr('name', ui.item.id); 
    } 
});? 
+0

好,它的工作原理。我只是做'成功:函数(数据,状态){$('#redir-loader')。hide();响应(数据); }',没有'error'和'complete'。谢谢。 – 2012-02-22 14:19:25

+0

我认为你完全可以依靠ajax回调:“beforeSend”显示加载器,“完成”隐藏。然后,您可以从自动填充中移除“搜索”和“打开”事件。 – 2012-02-22 14:20:45

+0

我知道了,谢谢。 :) – 2012-02-22 14:26:02