2017-06-01 118 views
1

我試圖找到一種方法來使用jQuery自動完成與PHP源獲取數據通過從服務器的ajax json對象列表。 但是選擇爲空:jQuery自動完成與ajax json phph

<script>$('#id_client_nc').autocomplete({ source: function(request, response) { $.ajax({ url: "<?php echo URL::base(); ?>commerce/client/selectajax/"+$(this).val(), dataType: "jsonp", 
     data: { 
     q: request.term 
     }, 
     success: function(data) { 

     var sel = $("#id_client_nc"); 
     sel.empty(); 

     $("#id_client_nc").empty(); 
     sel.append('<option value="">--sélectionner--</option>'); 
     for (var i=0; i<data.length; i++) 
     { 

      sel.append('<option value="' + data[i].client_id + '" >' + data[i].client_nom +'</option>'); 

     } 
     $("#id_client_nc").select2("destroy"); 
     $("#id_client_nc").select2(); 

     } 
    }); 
    } 

});

HTML:

<select name="" class="selecttwo-s span12 id_client" id="id_client_nc"> </select> 
+0

類似的問題,https://stackoverflow.com/questions/8090457/populating-select-option-dynamically-with-jquery – Blueline

回答

0

response參數是你與你的自動完成數據作爲參數調用一個函數。因此,在你的例子,假設你的數據是JSON格式的數組,你會寫

response(JSON.parse(data)); 

你的結果傳遞給自動完成窗口。