2017-04-06 175 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. 
 

 
     }); 
 
    });