考虑一个包含一些值的数组
array = {'microsoft','micromax', 'miniclip','michael jackson','million','milky way'}
当用户开始输入文本时,假设他/她正在尝试输入 million
。当用户开始输入 'mi'
时,数组中的上述建议将显示给用户。
我的问题:
让我们假设用户正在输入单词“mini clip”,由于打字错误,他/她开始输入 “mni”或“minc”或“nim”或“imn”或“nim”而不是“min” ',
这个场景还需要向用户展示建议。因为,无论如何,这些键入的字符在“miniclip”一词中可用。拼写错误对于所有入门级用户/普通用户来说都很常见。所以我需要 javascript/php/ajax/opensource 库中的代码来适应这种情况。
最佳答案
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
的子 div
以替换 的内容>#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
关于javascript - 自动建议 Javascript/PHP/AJAX 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19586792/