我觉得我有必要写这个教程,因为曾经见到的大部分关于自动完成的应用程序都只是给你一个程序源码包,然后告诉你怎么使用,而不是告诉你它是如何工作的以及为什么这样做。而知道这些可以让你对这个插件可以进一步的按自己的需求定制。
好,我们现在开始。
JavaScript代码 :
复制代码 代码如下:
<script src="jquery-1.2.1.pack.js" type="text/javascript"></script>
<script type="text/javascript">
function lookup(inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$(‘#suggestions').hide();
} else {
$.post("rpc.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$(‘#suggestions').show();
$(‘#autoSuggestionsList').html(data);
}
});
}
} // lookup
function fill(thisValue) {
$(‘#inputString').val(thisValue);
$(‘#suggestions').hide();
}
</script>
复制代码 代码如下:
// PHP5 Implementation - uses MySQLi.
$db = new mysqli(‘localhost', ‘root' ,”, ‘autoComplete');
if(!$db) {
// Show error if we cannot connect.
echo ‘ERROR: Could not connect to the database.';
} else {
// Is there a posted query string?
if(isset($_POST[‘queryString'])) {
$queryString = $_POST[‘queryString'];
// Is the string length greater than 0?
if(strlen($queryString) >0) {
// Run the query: We use LIKE ‘$queryString%'
// The percentage sign is a wild-card, in my example of countries it works like this…
// $queryString = ‘Uni';
// Returned data = ‘United States, United Kindom';
$query = $db->query("SELECT value FROM countries WHERE value LIKE ‘$queryString%' LIMIT 10");
if($query) {
// While there are results loop through them - fetching an Object (i like PHP5 btw!).
while ($result = $query ->fetch_object()) {
// Format the results, im using <li> for the list, you can change it.
// The onClick function fills the textbox with the result.
echo ‘<li>'.$result->value.‘</li>';
}
} else {
echo ‘ERROR: There was a problem with the query.';
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo ‘There should be no direct access to this script!';
}
}
?>
复制代码 代码如下:
<style type="text/css">
.suggestionsBox {
position: relative;
left: 30px;
margin: 10px 0px 0px 0px;
width: 200px;
background-color: #212427;
-moz-border-radius: 7px;
-webkit-border-radius: 7px;
border: 2px solid #000;
color: #fff;
}
.suggestionList {
margin: 0px;
padding: 0px;
}
.suggestionList li {
margin: 0px 0px 3px 0px;
padding: 3px;
cursor: pointer;
}
.suggestionList li:hover {
background-color: #659CD8;
}
</style>
还有,
最后就是有用的链接了,我想你应该期待很久了。
源文件 :点击下载
新闻热点
疑难解答