我有一个Bootstrap tyepahead,可以从我的数据库中获取实时数据。我希望能够返回多个值(图像链接和数据库中的其他信息),而不是仅从数据库中返回一个单词(人的用户名)。
HTML和jQuery / Ajax:
<input class="typeahead" type="text" data-provide="typeahead" autocomplete="off" placeholder="Type something...">
<script>
$('.typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: 'php/script.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data) {
process(data);
}
});
}
});
</script>
PHP:
<?php
include_once("connect_info.php");
$cxn = mysqli_connect($host, $user, $pass, $db) or die ("Couldn't connect to the server. Please try again.");
$return = array();
if(isset($_POST['query'])){
$stmt = $cxn->prepare('SELECT user_id FROM users WHERE username LIKE concat("%", ?, "%")');
$stmt->bind_param('s', $_POST['query']);
$stmt->execute();
while ($row = $result->fetch_assoc()) {
$return[] = $row['user_id'];
}
}
$json = json_encode($return);
print_r($json);
?>
如何做到这一点?
答案 0 :(得分:1)
您可以返回Json对象的数组。喜欢 [{user_name:&#34; XYZ&#34;,image_link:&#34; http://www.mysite.com/my_image} ....] 我在python中这样做,我相信你可以在PHP中做同样的事情。
请查看typeahead示例页面上的最后一个示例[最佳图片获胜者]。 http://twitter.github.io/typeahead.js/examples/
答案 1 :(得分:0)
我自己解决了这个问题,这比我想象的容易得多。
这是我的新代码:
HTML和jQuery / Ajax:
<input class="typeahead" type="text" data-provide="typeahead" autocomplete="off" placeholder="Type something...">
<script>
$('.typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: 'php/script.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data) {
process(data);
}
});
},
highlighter: function(data) {
var parts = data.split(','),
html = '<img src="pictures/' + parts[0] + '.jpg" />';
html += '<div class="info">' + parts[1] + '</div>';
return html;
},
});
</script>
PHP:
<?php
include_once("connect_info.php");
$cxn = mysqli_connect($host, $user, $pass, $db) or die ("Couldn't connect to the server. Please try again.");
$return = array();
if(isset($_POST['query'])){
$stmt = $cxn->prepare('SELECT user_id, username FROM users WHERE username LIKE concat("%", ?, "%")');
$stmt->bind_param('s', $_POST['query']);
$stmt->execute();
while ($row = $result->fetch_assoc()) {
$return[] = $row['user_id'] . ',' . $row['username'];
}
}
$json = json_encode($return);
print_r($json);
?>