jQuery UI自动完成(combobox):如何用AJAX请求的结果填充它?

Vit*_*mar 11 jquery-ui jquery-ui-autocomplete

是否可以像通常的jquery-ui ajax自动完成字段一样使用组合框

我需要的?

我希望有一些默认选项,当用户尝试输入任何字母时,它必须连接到服务器以查找请求的信息(通常是远程json自动完成).

有可能吗?

And*_*ker 11

这是jQueryUI示例(gist)的大量修改版本:

$.widget("ui.combobox", {
    _create: function() {
        var _self = this
            , options = $.extend({}, this.options, {
            minLength: 0,
            source: function(request, response) {
                if (!request.term.length) {
                    response(_self.options.initialValues);
                } else {
                    if (typeof _self.options.source === "function") {
                        _self.options.source(request, response);
                    } else if (typeof _self.options.source === "string") {
                        $.ajax({
                            url: _self.options.source,
                            data: request,
                            dataType: "json",
                            success: function(data, status) {
                                response(data);
                            },
                            error: function() {
                                response([]);
                            }
                        });
                    }
                }
            }
        });

        this.element.autocomplete(options);

        this.button = $("<button type='button'>&nbsp;</button>")
            .attr("tabIndex", -1)
            .attr("title", "Show All Items")
            .insertAfter(this.element)
            .button({
                icons: {
                    primary: "ui-icon-triangle-1-s"
                },
            text: false
            })
            .removeClass("ui-corner-all")
            .addClass("ui-corner-right ui-button-icon")
            .click(function() {
                if (_self.element.autocomplete("widget").is(":visible")) {
                    _self.element.autocomplete("close");
                    return;
                }
                _self.element.autocomplete("search", "");
                _self.element.focus();
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

用法:

$("input_element_selector").combobox({
    initialValues: ['array', 'of', 'values'],
    source: /* <-- function or string performing remote search */,
    /* any other valid autocomplete options */
});
Run Code Online (Sandbox Code Playgroud)

示例: http ://jsfiddle.net/Jpqa8/

initialValues当搜索长度为"0"时,窗口小部件使用提供的数组作为源(当用户单击下拉按钮时会发生这种情况).

提供source执行远程搜索的参数(函数或字符串).您还可以使用通常用于自动完成小部件的任何其他选项.