jQuery UI使用json文件自动完成

jQuery UI autocomplete with json file

本文关键字:文件 UI 使用 json jQuery      更新时间:2023-09-26

我的自动完成输入字段不起作用,我找不到原因。我使用的是一个外部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回调提供一个具有labelvalue属性的对象数组:

    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/