好吧,我一直在绞尽脑汁(我在这方面很糟糕),但是的,我试着尽我所能阅读,但仍然无法让它发挥作用.

try 使用jQuery UI执行自动完成

my json looks like this

{"dealers":
     {
         "1156":"dealer 1",
         "1122":"dealer 2",
         "1176":"dealer 3",
         "1491":"dealer 4",
         "1463":"dealer 5",
         "269":"dealer 6"
    }
}

我正在try 使用此信息作为自动完成的来源.我可以很好地获取响应对象,只是格式不正确,这样我就可以将"#"放在与"value"绑定的隐藏字段中,而"value"需要显示为下拉列表的一部分.

been trying a million different ways but a recent attempt was below

function ajaxCall() {
    $.getJSON("/example/location/example.json?term=" + $('#dealerName').val(),
        function(data) {
        $.each(data.dealers, function(k, v) {                
                alert(k + ' : ' + v);
        });
    });        
}

$('#dealerName').autocomplete({
    source: ajaxCall,
    minLength: 2,
    delay: 100
});

Please and thank you much!

推荐答案

You need to transform the object you are getting back into an array in the format that jQueryUI expects.

You can use $.map to transform the dealers object into that array.

$('#dealerName').autocomplete({
    source: function (request, response) {
        $.getJSON("/example/location/example.json?term=" + request.term, function (data) {
            response($.map(data.dealers, function (value, key) {
                return {
                    label: value,
                    value: key
                };
            }));
        });
    },
    minLength: 2,
    delay: 100
});

Note that when you select an item, the "key" will be placed in the text box. You can change this by tweaking the label and value properties that $.map's callback function return.

Alternatively, if you have access to the server-side code that is generating the JSON, you could change the way the data is returned. As long as the data:

  • Is an array of objects that have a label property, a value property, or both, or
  • 是一个简单的字符串数组

In other words, if you can format the data like this:

[{ value: "1463", label: "dealer 5"}, { value: "269", label: "dealer 6" }]

或者这个:

["dealer 5", "dealer 6"]

Then your JavaScript becomes much simpler:

$('#dealerName').autocomplete({
    source: "/example/location/example.json"
});

Json相关问答推荐

使用单元和非单元版本反序列化Rust中的枚举,而无需编写自定义反序列化程序

如何创建生成两个不同对象的JSON数组的SQL查询?

来自json的可分析的构建报告

使用快速json库编写json可以消除所有缩进

Oracle JSON 查询中的动态列列表

go 语言中的 JSON 到 XML

如何将一个对象添加到多个对象中 JOLT

Jolt 转换数组对象并将某些字段移动到嵌套数组

如何加入或合并列表元素列表(未知长度)

Scala - 在构建 Json 时无法删除 Key -> value "{}" 大括号的双引号

从 PowerShell 编辑 Windows 终端配置文件设置 JSON

jq搜索特定字符串并输出对应的父值

如何使用 gson 将数据保存在 json 文件中?

IE中Json响应下载(7~10)

Android JSON 库的性能和可用性比较

如何在 django rest 框架中定义列表字段?

在 JSON 编码的 HTML5 数据属性中转义/编码单引号

如何在java中比较来自JsonObject的空值

如何自动修复无效的 JSON 字符串?

jQuery循环.each()JSON键/值不起作用