php - 自动完成:使用远程数据源未检测到任何结果

标签 php javascript jquery jquery-ui autocomplete

上下文

  • 我使用 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);
    }
});

最佳答案

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

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

关于php - 自动完成:使用远程数据源未检测到任何结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9396272/

相关文章:

javascript - JS : How to choose random pairs of items from an array

javascript - 如何使用正则表达式转换字符串而不是数字中的字母?

Jquery插件获取DIV ID

jquery - 如何在 jQuery 中处理按钮点击事件?

php - 使用 MySQL 和 PHP 将数据存储在 MySQL 数据库中

php - CodeIgniter - 如何将表单中的值发布为 NULL 而不是 0

javascript - D3js : scale an axis on every bar chart

jQuery - "Selectors"和作为选择器传递的字符串之间混淆

javascript - 如何推送/播放 setTimeout 函数

php - 亚马逊灵活支付异常 : Caller Input Exception: Invalid Signature