我一直在想我的大腦數小時,試圖找出爲什麼這不起作用。預先感謝任何能夠提供幫助的人。我的Select2插件沒有通過ajax返回任何PHP腳本的結果
基本上,我試圖從php/mysql數據庫查詢中使用json編碼的數據來填充select2插件的下拉列表。
的HTML:
<input type="hidden" name="search-area" id="location-search" data-placeholder="Select an area" style="width:100%"/>
的JavaScript:
$(document).ready(function() {
$(".select2").select2();
$("#location-search").select2({
ajax: {
url: "location-data.php",
dataType: 'json',
data: function (term) {
return {
q: term
};
},
results: function (data) {
return { results: data.text };
}
}
});
})
PHP腳本 '位置data.php':
<?php
include 'db/db-connect.php';
$query = "SELECT townID, town FROM towns WHERE town LIKE '%a%' ORDER BY town";
$result = $db->query($query);
$numtowns = $result->num_rows;
if($numtowns != 0) {
while($row = $result->fetch_assoc()) {
$answer[] = array("id"=>$row['townID'], "text"=>$row['town']);
}
}
else {
$answer[] = array("id"=>"0", "text"=>"No Results Found...");
}
echo json_encode($answer);
?>
現在,我已經看過了位置 - data.php頁面在我的瀏覽器中,它以正確的格式顯示,見下文。
[{"id":"1","text":"basildon"},{"id":"2","text":"billericay"},{"id":"7","text":"eastwood"},{"id":"12","text":"hanningfield"},{"id":"5","text":"maldon"},{"id":"11","text":"ongar"},{"id":"6","text":"rayleigh"}]
每當我嘗試使用select2框時,它顯示的全部內容都是'搜索...',並且從不顯示結果。
再次感謝您提供的任何幫助。
另外,我使用 '一' 只是爲了得到它顯示的結果,一旦硬編碼搜索已經完成了,那麼我將繼續努力使結果變得動態。 – user3199248