我试图找到一个工作的twitter bootstrap typeahead元素的例子,将使ajax调用来填充它的下拉列表。
我有一个现有的工作jquery自动完成的例子,它定义了ajax url和如何处理回复
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
var options = { minChars:3, max:20 };
$("#runnerquery").autocomplete('./index/runnerfilter/format/html',options).result(
function(event, data, formatted)
{
window.location = "./runner/index/id/"+data[1];
}
);
..
我需要改变什么来转换这到typeahead的例子?
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
var options = { source:'/index/runnerfilter/format/html', items:5 };
$("#runnerquery").typeahead(options).result(
function(event, data, formatted)
{
window.location = "./runner/index/id/"+data[1];
}
);
..
我将等待“为typeahead添加远程源支持”问题得到解决。
从Bootstrap 2.1.0开始:
HTML:
<input type='text' class='ajax-typeahead' data-link='your-json-link' />
Javascript:
$('.ajax-typeahead').typeahead({
source: function(query, process) {
return $.ajax({
url: $(this)[0].$element[0].dataset.link,
type: 'get',
data: {query: query},
dataType: 'json',
success: function(json) {
return typeof json.options == 'undefined' ? false : process(json.options);
}
});
}
});
现在您可以创建统一的代码,在html代码中放置“json-request”链接。
从Bootstrap 2.1.0开始:
HTML:
<input type='text' class='ajax-typeahead' data-link='your-json-link' />
Javascript:
$('.ajax-typeahead').typeahead({
source: function(query, process) {
return $.ajax({
url: $(this)[0].$element[0].dataset.link,
type: 'get',
data: {query: query},
dataType: 'json',
success: function(json) {
return typeof json.options == 'undefined' ? false : process(json.options);
}
});
}
});
现在您可以创建统一的代码,在html代码中放置“json-request”链接。
$('#runnerquery').typeahead({
source: function (query, result) {
$.ajax({
url: "db.php",
data: 'query=' + query,
dataType: "json",
type: "POST",
success: function (data) {
result($.map(data, function (item) {
return item;
}));
}
});
},
updater: function (item) {
//selectedState = map[item].stateCode;
// Here u can obtain the selected suggestion from the list
alert(item);
}
});
//Db.php file
<?php
$keyword = strval($_POST['query']);
$search_param = "{$keyword}%";
$conn =new mysqli('localhost', 'root', '' , 'TableName');
$sql = $conn->prepare("SELECT * FROM TableName WHERE name LIKE ?");
$sql->bind_param("s",$search_param);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$Resut[] = $row["name"];
}
echo json_encode($Result);
}
$conn->close();
?>