如何在 Web 应用程序中使用条码扫描仪

我想在我的 Laravel 应用程序中使用条形码扫描仪.这是一个在线销售点应用程序.我知道条码扫描器只返回一个字符串,然后按 Enter 按钮.但是为了捕获这个字符串,我需要使用一个表单并选择输入字段.如果我不选择输入字段,它就无法捕获数据.我想要的是在不选择表格的情况下使用条形码扫描仪.有可能吗?

I would like to use barcode scanner in my Laravel application. This is an online Point of Sale Application. I know that barcode scanner returns just a string and press Enter Button. But to capture this string I need to use a form and select the input field as well. If I dont select the input field it cann't capture the data. What I want is to work the barcode scanner without selecting the form. Is it possible anyway ?

推荐答案

您可以使用 JavaScript 捕获条形码阅读器发送的按键.

You can capture the keypresses that the barcode reader sends with JavaScript.

向窗口或文档对象添加事件侦听器以捕获文档中任何位置的任何按键.检查传入字符中是否有表示条形码结束的字符(可能是新行).

Add an event listener to the window or document object to capture any keypresses anywhere in the document. Check the incoming characters for one which signals the end of the barcode (probably a new line).

这是我使用 RFID 阅读器为类似任务编写的一些代码.它取决于 jQuery(主要是因为 jQuery 对 event.which 进行的规范化使得识别按下的字符变得方便)但是如果您愿意,您可以重写它以避免这种情况.

This is some code I wrote for a similar task using an RFID reader. It depends on jQuery (mostly because the normalisation jQuery does on event.which makes identifying the character pressed convenient) but you can rewrite it to avoid that if you like.

它将每个按键存储在一个数组中,除非按键是 Enter(我使用的 RFID 阅读器在每次扫描后发送).如果它得到一个回车,它接受扫描的代码并对其进行操作(我正在使用 Socket.IO 将它发送到服务器,你可以用它做任何你喜欢的事情)然后清除数组,以便下一次扫描可以从新鲜开始.

It stores each keypress in an array unless the press is of Enter (which the RFID reader I was using sent after each scan). If it gets an Enter, it takes the scanned code and acts on it (I'm using Socket.IO to send it to the server, you can do whatever you like with it) and then clears the array so that the next scan can start from fresh.

var keybuffer = [];

function press(event) {
  if (event.which === 13) {
    return send();
  }
  var number = event.which - 48;
  if (number < 0 || number > 9) {
    return;
  }
  keybuffer.push(number);
}

$(document).on("keypress", press);

function send() {
  socket.emit('scan', keybuffer.join(""));
  keybuffer.length = 0;
}

相关文章