【问题标题】:How to hookup jQuery autocomplete with POST query to remote data source?如何将带有 POST 查询的 jQuery 自动完成功能连接到远程数据源?
【发布时间】:2013-02-21 22:46:19
【问题描述】:

我正在尝试使用 POST 查询将文本字段连接到带有远程数据源的 jQuery UI 自动完成功能。到目前为止,我有这个:

$( "#booking_student" ).autocomplete({
            source: function( request, respond ) {
                $.post( "/path/to/my/api.php", { student: request.term },
                        function( response ) {
                            //do something
                        } );
            }
        });

使用 Firebug,我可以看到我的 API 正在返回我期望的结果,但没有出现自动完成下拉菜单。我需要做什么才能将结果插入自动完成下拉菜单?我是否需要在 //do something 部分使用 JSON 结果填充变量?

【问题讨论】:

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


    【解决方案1】:

    您需要将结果提供给小部件为您提供的respond 回调:

    $( "#booking_student" ).autocomplete({
        source: function( request, respond ) {
            $.post( "/path/to/my/api.php", { student: request.term },
                function( response ) {
                    respond(response);
            });
        }
    });
    

    这当然假设您的数据是一个数组,其中的项目包含label 属性、value 属性或两者。这在documentation for the source option 中有概述。

    【讨论】:

    • 很好的答案,可能需要注意,将数据类型添加到$.post() 作为第四个参数可能是有益的。有时可能需要在末尾简单地添加, "json"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    相关资源
    最近更新 更多