【问题标题】:Instane search delay 1 character即时搜索延迟 1 个字符
【发布时间】:2015-10-13 06:41:11
【问题描述】:

这是我的 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 个字符...

【问题讨论】:

    标签: javascript php ajax regex post


    【解决方案1】:

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

    改成onkeyup

    onkeydown="searchq()"
    

    应该是

    onkeyup="searchq()"
    

    keyup:

    当用户释放一个键时触发,在该键的默认操作已经执行之后。


    我会推荐你​​使用 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);
            });
        });
    });
    

    【讨论】:

    • 还有什么需要改变的吗?因为你给我的新方法行不通……
    • @user3081581 你必须在ready 中包装代码,检查更新的代码
    • @tushar 嗨...你能教我如何做一个范围搜索功能...例如,我想从 valueA 搜索到 valueB...
    猜你喜欢
    • 2013-02-24
    • 1970-01-01
    • 2018-08-02
    • 2019-02-27
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多