2015-04-03 94 views
1

我的自動完成輸入字段不起作用,我找不到原因。我正在使用外部JSON文件,如下所示:jQuery UI自動完成與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"} 
]} 

爲了清楚起見,我選擇了多維數組。下面是自動完成的

$(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輸入我的JavaScript文件:

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

我想顯示自動完成輸入內部節點的標籤,如果有人可以幫助我進入到節點的標籤。謝謝 !

回答

0
  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/

+0

謝謝你的幫助@nikoshr。但是我還有一個問題,是否必須將我的JSON文件的內容放入'var'或不是?因爲如果我的autocomple的'source'是一個將過濾請求的函數,我不能再使用我的JSON文件了? – suniz 2015-04-03 11:48:17

+0

我不確定我是否理解你的問題,你的文件內容可以通過'data'參數在'success'回調中獲得。如果您指的是我在Fiddle中設置的方式,那只是一個演示,您不必在應用程序中複製文件的內容。基本上,只需更換你的回調,你應該沒問題。 – nikoshr 2015-04-03 12:03:34

+0

我問了我的問題後,我想出了它。再次感謝您的幫助。 – suniz 2015-04-03 12:28:19