gpt4 book ai didi

javascript - 即时搜索延迟1个字符

转载 作者:行者123 更新时间:2023-11-30 00:25:29 26 4
gpt4 key购买 nike

这是我的 Ajax 脚本

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function searchq() {
var searchTxt = $("input[name='search']").val();

$.post("search1.php", {
searchVal: searchTxt
}, function(data) {
$("#data").html(data);
});
}
</script>

这是我的表单代码

<form action="search1.php" method="post">
<input type="text" name="search" placeholder="Search" onkeydown="searchq()">
</form>
<div id="data"></div>

这是我的php代码

<?
$file = fopen('aws.csv', 'r');
$output ='';
if (isset($_POST['searchVal'])) {
$words = $_POST['searchVal'];

$words = array(preg_replace("#[^0-9a-z]#"," ",$words));

$words = array_map('preg_quote', $words);
// The argument becomes '/wii|guitar/i', which means 'wii or guitar, case-insensitive'
$regex = '/'.implode('|', $words).'/i';


while (($line = fgetcsv($file)) !== FALSE) {
list($name, $age, $hobbies) = $line;

if(preg_match($regex, $age)) {
$output .= "$name, $age, $hobbies<br/>";
}

}
}
echo $regex;
echo $output;
?>

我的问题是当我在搜索框中输入“Hello”之类的值时...($regex) 的输出将显示/Hell/i 而不是显示/Hello/i ... 它的延迟 1 个字符...

最佳答案

因为您使用的是 onkeydown,所以在将键值添加到文本框中之前会触发该事件。

将其更改为onkeyup

onkeydown="searchq()"

应该是

onkeyup="searchq()"

keyup :

Fires when the user releases a key, after the default action of that key has been performed.


我建议您使用 jQuery 而不是内联来处理事件。

$(document).ready(function() {
$("input[name='search']").on('keyup', function() {
$.post("search1.php", {
searchVal: $.trim($(this).val()) // Trim: Remove leading & trailing spaces
}, function(data) {
$("#data").html(data);
});
});
});

关于javascript - 即时搜索延迟1个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31579228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com