我正在为一个研究所做实习生的门户网站。
目前在电话簿上制作模块。我的导师要求我在文本字段上应用AJAX以输入员工姓名。我通过phpMyAdmin使用Dreamweaver CS4和MySQL数据库。
我的问题是:如何在文本字段上应用AJAX,以便整个员工姓名列表在输入单个字符时显示为列表。它和Google一样,它给出了建议。我搜索了很多,没有得到任何代码。此外,Dreamweaver的功能非常有限,而且使用起来也很困难。
答案 0 :(得分:0)
我猜这两个链接可能会帮助你达到你想要的效果。 http://beski.wordpress.com/2009/11/20/jquery-php-mysql-ajax-autocomplete/。 http://jqueryui.com/autocomplete/
答案 1 :(得分:0)
我有一个很好的解决方案,如果你使用Twitter Bootstrap,我会从另一个帮助你的问题中被部分窃取(如果你还没有,那么值得整合,相信我,它会让你的生活更容易):
所以这是名称的文本字段的代码:
<form class="navbar-search">
<input type="text" id="search" class="search-query span3 pull-right" placeholder="Search" data-provide="typeahead">
<div class="icon-search"></div>
</form>
接下来,您需要一些jQuery代码来执行AJAX部分:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-1.9.0.min.js"><\/script>')</script>
<!-- Bootstrap jQuery plugins compiled and minified -->
<script src="js/bootstrap.min.js"></script>
<!-- Bootstrap JS Code -->
<script>
$(document).ready(function(){
$('#search').typeahead({
source: function(query, process) {
$.ajax({
url: 'database.php'
type: 'POST';
data: 'query=' + query;
dataType: 'JSON';
async: true;
success: function(data) {
process(data);
}
});
}
});
});
</script>
最后,您需要创建database.php,它将搜索您的数据库并将值返回到您的搜索栏:
<?php
if (isset($_POST['query'])) {
// Connect to database
mysql_connect('[database url]','[username]','[password]');
mysql_select_db('[database name]');
// Retrieve the query
$query = mysql_real_escape_string($_POST['query']);
// Search the database for all similar items
$sql = mysql_query("SELECT * FROM names WHERE name LIKE '%{$query}%'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['name'];
}
// Return the json array
echo json_encode($array);
}
?>