自动完成:检测不到远程数据源的任何结果

Autocomplete: detect no results with remote datasource

本文关键字:数据源 结果 任何 检测      更新时间:2023-09-26

上下文

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

问题

如何检测搜索是否没有隐藏加载程序gif的结果?

代码

jquery:

$('#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);
    }
});

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

_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);
    }
});?