华域联盟 JAVA js获取USB扫码枪数据的方法

js获取USB扫码枪数据的方法

本文实例为大家分享了js获取USB扫码枪数据的具体过程,供大家参考,具体内容如下

废话不多说,直接上代码,这个方法避免了 首字缺失,字符串乱码等等问题,特别好用,记录一下

中间的Ajax可直接调用登录功能,实现自动登录

说明:输入框需要获得焦点,这个是必须的,其次为了防止回车触发手动登录,需要添加οnkeypress="if(event.keyCode==13) return false;"这个操作,这个在回车的时候,输入框焦点不会丢失,除非手动切换焦点,或者调用focus();方法

<div class="form-group">
 <label for="inputUsernameEmail">账号</label>
 <input type="text" placeholder="请输入账号" name="username" id="loginname" class="form-control" autofocus onkeypress="if(event.keyCode==13) return false;">
</div>

代码:

<script>
  window.onload = (e)=> {
   this.start = new Date().getTime()
   let code = ''
   let lastTime, nextTime
   let lastCode, nextCode
   let that = this
   window.document.onkeypress = function (e) {
    if (window.event) { // IE
     nextCode = e.keyCode
    } else if (e.which) { // Netscape/Firefox/Opera
     nextCode = e.which
    }
    console.log('nextCode', nextCode)
    if (e.which === 13 || window.event === 13) {
     var deviceCode = code;
     console.log(code)
     console.log('扫码结束')
     console.timeEnd()
     code = ''
     lastCode = ''
     lastTime = ''
     $.ajax({
      cache: true,
      type: "POST",
      url: rootPath + "/admin/login",
      data: {code: deviceCode, type: 1},
      async: false,
      error: function (request) {
       $("#loginname").val("");
       $.modal.alertError("系统错误");
      },
      success: function (data) {
       $("#loginname").val("");
       if (data.code == 200) {
        location.href = rootPath + '/admin/index';
       } else {
        $.modal.alertError(data.msg);
       }
      }
     });
    }
    nextTime = new Date().getTime()
    if (!lastTime && !lastCode) {
     console.log('扫码开始。。。')
     code += e.key
    }
    if (lastCode && lastTime && nextTime - lastTime > 500) { // 当扫码前有keypress事件时,防止首字缺失
     console.log('防止首字缺失。。。')
     code = e.key
    } else if (lastCode && lastTime) {
     console.log('扫码中。。。')
     code += e.key
    }
    lastCode = nextCode
    lastTime = nextTime
   }
  }
</script>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » js获取USB扫码枪数据的方法

转载请保留出处和原文链接:https://www.cnhackhy.com/82429.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部