javascript 用于 Jquery 自动完成的 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4184818/
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-10-25 10:37:26  来源:igfitidea点击:

JSON for Jquery autocomplete

javascriptjqueryjsonjquery-ui

提问by Castro

I've JSON response from php file.

我有来自 php 文件的 JSON 响应。

[{
  "NAME": "Kiev"
}, {
  "NAME": "Kiev metro"
}, {
  "NAME": "Kiev-Dnepro"
}, {
  "NAME": "Kiev-Dnepro"
}, {
  "NAME": "Kiev-Donetsk"
}, {
  "NAME": "Kiev-Donetsk"
}]

How can I use that for standard Jquery autocomplete? Autocomplete function do request but it seems it cant parse response for this json (simple array works fine). Help me please

我如何将它用于标准的 Jquery 自动完成?自动完成功能确实有请求,但它似乎无法解析此 json 的响应(简单数组工作正常)。请帮帮我



Derin, yes that's it. Works fine! But now I want to modify it a little. I getting more data in response and I'd like to display it near of main autocomplete input

德林,是的,就是这样。工作正常!但现在我想稍微修改一下。我收到了更多数据作为响应,我想在主自动完成输入附近显示它

var infoGISName = null;
var infoGISType = null;
var infoGISLocationID = null;
var infoGISParentID = null;

$('#GISName').autocomplete({
source: function(request, response) {
  $.getJSON("autocomplete.php", {
    term: request.term
  }, function(result) {
    response($.map(result, function(item) {
      infoGISName = item.NAME;
      infoGISType = item.GIS_TYPE;
      infoGISLocationID = item.LOCATION_ID;
      infoGISParentID = item.PARENT_ID;
      return item.NAME;
    }));
  });
},
change: function(event, ui) {
  $('#infoGISName').html(infoGISName);
  $('#infoGISType').html(infoGISType);
  $('#infoGISLocationID').html(infoGISLocationID);
  $('#infoGISParentID').html(infoGISParentID);
},
minLength: 3

});
});

So how to change data in fields when I changed text in autocomplete input? Now I see just last values from JSON recordset

那么当我在自动完成输入中更改文本时如何更改字段中的数据?现在我只看到 JSON 记录集中的最后一个值

回答by Darin Dimitrov

You could use the formatItemoption:

您可以使用该formatItem选项:

$('#foo').autocomplete({ 
    url : '/foo', 
    formatItem: function(item, position, length) {
        return item.NAME;
    } 
});


For the jquery ui autocomplete here's how you could achieve this:

对于 jquery ui 自动完成功能,您可以通过以下方式实现:

$('#foo').autocomplete({
    source: function(request, response) {
        $.getJSON('/foo.php', { q: request.term }, function(result) {
            response($.map(result, function(item) {
                return item.NAME;
            }));
        });
    }
});