1
我剛剛開始使用PDO方法查詢數據庫,並且遇到了一些絆腳石。向Twitter引導PDO語句的JSON輸出
我在做什麼:用簡單查詢的結果填充一個typeahead字段。
代碼來查詢數據庫:
$query = $db->prepare("SELECT `customers`.`Name` FROM `customers` WHERE `customers`.`Name` LIKE :searchterm");
$searchterm = (isset($_POST['searchterm']) === true) ? $_POST['searchterm'] : '';
$query->bindValue(':searchterm', '%' . $searchterm . '%');
$query->execute();
$rows=$query->fetchAll(PDO::FETCH_ASSOC);
echo(json_encode($rows));
Javascript功能來填充預輸入:
$('#customer-name').typeahead({
source: function (query, process) {
return $.post('ajax/get_customer_names.php', { searchterm: query }, function (data) {
console.log(data);
return process(data);
});
}
});
現在我知道了預輸入期望字符串按以下格式
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
數組問題是我的代碼現在通過發送到console.log輸出它s格式
[{"Name":"test"},{"Name":"Southern Testing"}]
我一直在這個問題上一整天都陷入困境,沒有找到合適的例子。我假設我需要遍歷$ rows變量並提取字符串值,但不知道如何實現這一點。 任何人都可以讓我知道我哪裏錯了,並提供解決方案嗎?
好吧我找到了解決這個問題的答案使用這個問題的答案http://stackoverflow.com/questions/13687797/twitter-bootstrap-typeahead-with-json但是使用這種方法的處理是由瀏覽器不理想。任何解決方案使用服務器端處理 –