使用 JSON 数据自动完成 jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11532202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:42:43  来源:igfitidea点击:

AutoComplete jQuery Using JSON data

jqueryajaxjsonjquery-uijquery-ui-autocomplete

提问by silentw

Imagine a json file with the following data:

想象一个包含以下数据的 json 文件:

[
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    },
    {
        color: "blue",
        value: "#00f"
    },
    {
        color: "cyan",
        value: "#0ff"
    }
]

Using jQuery's autocomplete method, I want it to be able to display the coloras options to select and insert valueon a input.

使用 jQuery 的自动完成方法,我希望它能够将颜色显示为在输入上选择和插入值的选项。

<input type="text" name="selector" id="selector" />

<input type="text" name="color" id="color" />
<input type="text" name="value" id="value" />

The above doesn't need introductions. Selector for the search on the colors, input.colorwith colorvalue and input.valuewith valuevalue.

以上无需介绍。选择对的颜色的搜索,input.color色彩值,并input.value价值的价值。

EDIT:I have this JSON data:

编辑:我有这个 JSON 数据:

[{
    "label": "Sec\u00e7\u00e3o 1",
    "value": "1"
}, {
    "label": "Sec\u00e7\u00e3o 2",
    "value": "2"
}, {
    "label": "Sec\u00e7\u00e3o 3",
    "value": "3"
}, {
    "label": "Sec\u00e7\u00e3o 4",
    "value": "4"
}]

and this HTML:

和这个 HTML:

<input type="text" id="name" />
<input type="text" id="value" />

and this jQuery:

和这个jQuery:

$(document).ready(function(){
    $("#name").autocomplete({
        source: "json.php",
        select: function (event, ui) {
            $("#name").val(ui.label);
            $("#value").val(ui.value);
        }
    });
});

I followed Andrew's answer and it prompts me to select the data, but if I alert ui.labeland ui.valuevariables, it says 'undefined'. What am I missing?

我遵循了安德鲁的回答,它提示我选择数据,但是如果我发出警报ui.labelui.value变量,它会显示“未定义”。我错过了什么?

Edit2:Let's say I have this HTML:

Edit2:假设我有这个 HTML:

<input type="text" class="name" />
<input type="text" class="value" />

<input type="text" class="name" />
<input type="text" class="value" />

Is it possible to handle multiple selectors with the same .autocomplete()method? Like, select the label I want using the input.nameand only update the input.valuenext to it?

是否可以使用相同的.autocomplete()方法处理多个选择器?比如,选择我想要使用的标签input.name并只更新它input.value旁边的标签?

[input.name] [input.value]
^ I select       ^ updates the
  a label           value next to it
[input.name] [input.value]
^ this stays intact ^

[input.name] [input.value]
^ 我选择 ^ 更新
  它旁边的标签值
[input.name] [input.value]
^ 这保持不变 ^

回答by Andrew Whitaker

Using a remote data source:

使用远程数据源:

$("#selector").autocomplete({
    source: function (request, response) {
         $.ajax({
             url: "my_server_side_resource.php",
             type: "GET",
             data: request,
             success: function (data) {
                 response($.map(data, function (el) {
                     return {
                         label: el.color,
                         value: el.value
                     };
                 }));
             }
         });
    },
    select: function (event, ui) {
        // Prevent value from being put in the input:
        this.value = ui.item.label;
        // Set the next input's value to the "value" of the item.
        $(this).next("input").val(ui.item.value);
        event.preventDefault();
    }
});

Tweak the $.ajaxcall as needed. This example will generate requests to your PHP resource that look like this:

$.ajax根据需要调整呼叫。此示例将生成对您的 PHP 资源的请求,如下所示:

my_server_side_resource.php?term=xyz

my_server_side_resource.php?term=xyz

If you have control over your server-side code, you could change the data that's returned to look like this:

如果您可以控制服务器端代码,则可以将返回的数据更改为如下所示:

[
    {
        label: "red",
        value: "#f00"
    }, /* etc */
]

You can simply use a string, the name of your server-side resource as the source:

您可以简单地使用一个字符串,您的服务器端资源的名称作为source

$("#selector").autocomplete({
     source: "my_server_side_resource.php",
     select: /* same as above */
});

Check out the remote with JSONP examplefor a full example using a server-side resource.

查看带有 JSONP远程示例以获取使用服务器端资源的完整示例。

Edit:See this example for a working demo using local data: http://jsfiddle.net/SMxY6/

编辑:有关使用本地数据的工作演示,请参阅此示例:http: //jsfiddle.net/SMxY6/

回答by solidau

You need to change your JSON object to use the "label" property. From the docs:

您需要更改 JSON 对象以使用“标签”属性。从文档:

An Array of Objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.

具有标签和值属性的对象数组:[ { label: "Choice1", value: "value1" }, ... ]

label 属性显示在建议菜单中。在用户从菜单中选择某些内容后,该值将被插入到 input 元素中。如果只指定了一个属性,它将用于两者,例如。如果您仅提供 value-properties,则该值也将用作标签。

Then, you need to set the values of the other text fields when the "change" or "select" events are fired.

然后,您需要在触发“更改”或“选择”事件时设置其他文本字段的值。

回答by Debasish Ghosh

After hours of working.. Finally made it happen. Thing is I have a json array consisting of many json objects. Each json object has bank name and its ifsc code.User needed to Type bank and filter out bank detail row from database. Upon selecting that bank... I had 2 input fields one for bank and other for ifsc code. I select bank name and corresponding ifsc code is shown. So this is how i did it:-

经过几个小时的工作..终于实现了。事情是我有一个由许多 json 对象组成的 json 数组。每个 json 对象都有银行名称及其 ifsc 代码。用户需要输入银行并从数据库中过滤出银行详细信息行。选择该银行后...我有 2 个输入字段,一个用于银行,另一个用于 ifsc 代码。我选择银行名称并显示相应的 ifsc 代码。所以我就是这样做的:-



<script type="text/javascript">
$(function() {





    $("#newBeneBankName").autocomplete({

        source: function(request, response) {

            $.ajax({
                url: "getBankDetailsIFSCJson",
                type: "GET",
                data: {
                    term: request.term
                },
                dataType: "json",
                success: function (data) {
                    response($.map(data, function (el) {
                        return {
                            label: el.label,
                            value: el.value
                        };
                    }));
                }
            });
        }, //newBeneBankName addBeneIfscCode
        focus: function (event, ui) {
            event.preventDefault();
            $("#newBeneBankName").val(ui.item.label);
        },
        select: function (event, ui) {
            event.preventDefault();
            $("#addBeneIfscCode").val(ui.item.value);
            $("#newBeneBankName").val(ui.item.label);
        }

});
});



my json array= [ { label:"state bank of india", value:"SBIN00076" }, { label:"ICICI Bank", value:"ICIC001" },.. ]

我的json数组= [{标签:“印度国家银行”,价值:“SBIN00076”},{标签:“ICICI银行”,价值:“ICIC001”},..]

回答by midhu

$(function() {
            $("#subject_name").autocomplete({
                    source: function(request, response) {
                        $.ajax({
                            url: "api/listBasicsubject",
                            dataType: "json",
                            type: "POST",
                            data: {
                                subject_name: request.term,

                            },
                            success: function(data) {
                                response($.map(data.data, function(item) {
                                        return {
                                            label: item.subject_name,
                                            value: item.subject_name

                                        }
                                    });
                                }


                            },
                            autoFocus: true,
                            minLength: 1
                        });
                    });
            });