jQuery UI 使用 json 文件自动完成

jQuery UI autocomplete with json file

我的自动完成输入字段不起作用,我找不到原因。我正在使用一个看起来像这样的外部 JSON 文件:

{
  "nodes": [
  {"id": "nt", "data": {
        "class": "date",
        "label": "Expositions New Tendencies",
        "tooltip": "New Tendencies Exhibition",
        "content": "Ceci est une visualisation de donnée concernant les différentes expositions sous le nom de 'New Tendencies', et regroupe les différents artistes, et leurs oeuvres. Pour parcourir la visualisation, cliquez sur les différents noeuds !",
        "graphicFillColor": "#fff",
        "graphicSize": 80,
        "labelFontSize": 18,
        "labelFontWeight": "regular",
        "labelPosition": "right"
    }}],

 "edges": [   
  {"source": "nt1", "target": "AdrianMarc"}
]}

所以为了清楚起见,我选择了多维数组。这是我的 JavaScript 文件,自动完成

$(function() {
    $('#recherche').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "feature-tour.json",
                dataType: 'json',
                data: request,
                success: function( data ) {
                    response( $.map( data, function( item ) {
                        console.log(item.nodes.id);
                        return(item.nodes.id)
                    }));
                }
            }); 
        },  
        minLength: 0
    });
});

和 HTML 输入:

<input type="text" id="recherche" placeholder="→ Rechercher un artiste"/>

如果有人可以帮助我访问节点标签,我想在自动完成输入中显示节点标签。谢谢!

  1. 您的节点在您的文件中作为 nodes 键公开,因此您应该遍历 data.nodes,而不是 data

    success: function(data) {
        var filtered = $.map(data.nodes, function(item) {
        // ...
        });
        response(filtered);
    }
    
  2. 您可能想要提供 response 回调 an array of objects with label and value properties :

    success: function(data) {
        var filtered = $.map(data.nodes, function(item) {
            return {
                label: item.data.label,
                value: item.id
            };
        });
        response(filtered);
    }
    
  3. 别忘了在调用回调之前,您必须自己在服务器端或客户端进行过滤。这是一个示例,其中标签必须包含查询(不区分大小写)

    success: function(data) {
        var query = request.term.toLowerCase(),
            filtered;
    
        filtered = $.grep(data.nodes, function(item) {
            return item.data.label.toLowerCase().indexOf(query) !==-1 ;
        });
    
        filtered = $.map(filtered, function(item) {
            return {
                label: item.data.label,
                value: item.id
            };
        });
    
        response(filtered);
    }
    

还有一个演示 http://jsfiddle.net/fh93xue4/2/