js实现连续输入之后发送请求

输入框是我们经常会用到的功能,想要实现输入就请求的功能

但是在实际开发中,为了减少服务器压力,会在输入之后停留1s没有输入之后再进行搜索

研究之后用原生js及表单写了一个简单的demo,如果有好的demo也可以留言大家一起交流

实现效果如下:

html代码

<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Untitled Document</title>
</head>

<body>
    <input type="text" onkeyup="send()" class="box">
</body>

</html>

js代码

<script src="./jquery-3.0.0.min.js"></script>
<script>
    let count = 0, timer = '', val = ''
    function send() {
        // 初始化
        count = 0
        if (timer) {
            clearInterval(timer)
        }
        // 获取输入值
        if (val.length != $('.box').val().length) {
            val = String($('.box').val())
            if (!val.length) {
                return
            }
        }
        // 定时器判断空闲时发送请求
        timer = setInterval(function () {
            ++count
            if (count >= 10) {
                console.log(`发送请求,参数:${val}`);
                clearInterval(timer)
            }
        }, 100)
    }
</script>

猜你喜欢

转载自www.cnblogs.com/cap-rq/p/11521042.html