检测用户是否连续输入减少ajax请求次数

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style type="text/css">
* {
    margin: 0;
    ;
    padding: 0;
}
.main {
    padding-top: 50px;
    width: 300px;
    margin: 0 auto
}
#test {
    width: 300px;
    height: 30px;
    line-height: 30px;
}
.ts {
    display: none;
    margin-top: 2px;
    width: 282px;
    padding: 10px;
    height: 200px;
    word-break: break-all;
    background: #333;
    color: #CCC;
    border: 1px solid #ccc;
    overflow-x: hidden;
}
</style>
<script type="text/javascript" src="jquery-1.4.2.min.js" ></script>
<script type="text/javascript">
$(function () {
    /*发送ajax请求*/
    function getdata(datas) {
        console.log("发送ajax 请求"+datas);
        /*若请求成功则显示提示的div*/
        $(".ts").html("提示内容"+datas).show();
    }
   
    function isonwrite(tid,ajaxfn) {
        var id;
        $('#' + tid).focus(function () {
            var k = "";
            var d = new Date("January 1,1970"),
                d2, k2;
            $('#' + tid).keydown(function (e) {
                $(".ts").hide();
            }).keyup(function (e) {
                /*字母数字退格delete、空格、回车键*/
                if (e.keyCode >= 48 && e.keyCode <= 90 || e.keyCode == 8 || e.keyCode == 46 || e.keyCode == 32 || e.keyCode == 13) {
                    k = $(this).val();
                    d = new Date();
                }
            });
           
            /*设置不间断监测*/
            id = setInterval(function () {
                d2 = new Date();
                /*如果输入框内容有变化且大于时间间隔,则发送一次请求*/
                if (k != "" && k2 != k && d2.getTime() - d.getTime() > 800){
                    k2 = k;
                    ajaxfn(k2);
                }
            }, 500);
         })
         
        /*失去焦点的时候清除监测函数*/
        $('#' + tid).blur(function () {
            clearInterval(id);
            id = null;
        })       
    }   
    isonwrite("test",getdata);
})
</script>
</head>
<body>
<div class="main">
  <input type="text" id="test" size="35" />
  <div  class="ts" ></div>
</div>
</body>
</html>

相关推荐