HTML
<form action=""><input type="text" name="word" id="word"></form>
<div id="auto"></div>
JS
$(function(){
$('#word').keyup(function(e){
var input = $(this).val();
$.ajax({
type: "get",
url: "autocomplete.php",
data: {word: input},
async: true,
success: function(data){
var outWords = $.parseJSON(data);
$('#auto').html('');
for(x = 0; x < outWords.length; x++){
$('#auto').prepend('<div>'+outWords[x]+'</div>'); //Fills the #auto div with the options
}
}
})
})
});
别忘了链接jQuery...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
注意
您需要执行一些操作,例如将onclick 事件添加到#auto 的子divs 以替换#word(输入字段)的内容。
PHP
$array = array('microsoft','micromax', 'miniclip','michael jackson','million','milky way');
$input = urldecode($_GET['word']); //Get input word/phrase (decode in case of spaces etc.)
$length = strlen($input); //Get length of input word
// $min = $length - 1; //Length of word - 1
// $max = $length + 1; //Length of word + 1
$returned = preg_grep('/^(['.$input.']{'.$length.'}.*)$/i', $array); //Find matches in $array and return as array
$returned = array_values($returned); //Re-index from 0
echo json_encode($returned); //Returm json string to ajax call
正则表达式
/^([$input]{$length}.*)$/i
-
/ => 开始分隔符
-
^ => 字符串开始
-
( => 启动捕获组
-
[ => 开始一个字符类
-
$input => 将输入词添加到字符类中
-
] => 结束字符类(4)
-
{$length} => 设置字符串长度以匹配字符类(输入单词的长度)
-
.* => 匹配任何以下字符 0 次或多次
-
) => 结束捕获组 (3)
-
$ => 匹配字符串结尾
-
/ => 结束分隔符
-
i => 不区分大小写的修饰符
最小/最大
我已包含注释的 $min 和 $max 变量...我认为您可能喜欢的附加功能...您可以通过更改来实现它们:
{'.$length.'} <-- Change this
{'.$min.','.$max.'} <--To that
{'.$length.','.$max.'} <-- Or that (or another combination)
示例
一个例子可能最好地说明它是如何工作的......
假设一个自动正确的数组:
$array = array('loser', 'loses', 'losing');
和一个输入:
lose
目前 ({'.$length.'}) 代码将返回:
loser
loses
但是如果你把它改成{'.$min.','.$max.'}(并且取消注释$min/$max);它会返回:
losing
loser
loses