2017-04-06 230 views
0

我正在爲一個項目構建一個小網站,並且我一直在尋找幾小時如何使用Materialize插件填充我的自動填充輸入。我對json或ajax不是很熟悉,所以我真的很痛苦。來自doc的原始示例像這樣帶有靜態數據:使用json數據填充實現自動填充

$('input.autocomplete').autocomplete({ 
data: { 
    "Apple": null, 
    "Microsoft": null, 
    "Google": 'http://placehold.it/250x250' 
}, 
limit: 20, // The max amount of results that can be shown at once. Default: Infinity. 
onAutocomplete: function(val) { 
    // Callback function when value is autcompleted. 
}, 
minLength: 1, // The minimum length of the input for the autocomplete to start. Default: 1. 
}); 

我希望能從我的數據庫中獲取動態數據。 我使用這個PHP代碼這樣做:

<?php 
     $query = $arg; 
     echo $query; 

     $json_output = array(); 
     $reponse = $bdd->query("SELECT CPnom FROM competence where CPnom LIKE ". $query); 

     while ($donnees = $reponse->fetch()) { 
        $json_output[] = $donnees[0]. ": null"; 
         } 

     return json_encode($json_output); 
?> 

我假設代碼工作,因爲它顯示[「JAVA」:空,「JS」:空,「C」:空]與我的數據庫數據相匹配。 任何想法如何把這個JSON數據在這個數據參數,而不是靜態名稱?

data: { 
    "Apple": null, 
    "Microsoft": null, 
    "Google": 'http://placehold.it/250x250' 
} 

謝謝你的時間!

回答

0

var data_2 = JSON.parse(sessionStorage.getItem('key_1')); 
 

 
    $(function() { 
 

 
     $('input.autocomplete').autocomplete({ 
 
     data: data_2, 
 

 
    limit: 20, // The max amount of results that can be shown at once. Default: Infinity. 
 
    onAutocomplete: function(val) { 
 

 
     // Callback function when value is autcompleted. 
 
    }, 
 
    minLength: 2 // The minimum length of the input for the autocomplete to start. Default: 1. 
 

 
     }); 
 
    });