如何使用js獲取USB掃碼槍資料
阿新 • • 發佈:2021-10-10
這篇文章主要為大家詳細介紹了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>
以上就是本文的全部內容,希望對大家的學習有所幫助