日期:2014-05-16  浏览次数:20487 次

JavaScript 扫描枪应用(三)
    实现原理:将Object标签以字符串的形式添加到页面的body中,通过attachEvent方式为AxtiveX添加响应事件,采用延迟读取缓存串口信息完成串口通信,利用执行回调函数完成参数与页面的参数传递与响应。以下是具体实现过程:

mscomm.js文件内容:
// JavaScript Document

function createMSComm(callBackFunction) {	
	var mscomm_str = "<OBJECT id=MSComm1 CLASSID='clsid:648A5600-2C6E-101B-82B6-000000000014' codebase='MSCOMM32.OCX' type='application/x-oleobject'  style='width:100px;height:30px' >"	
		+"<PARAM NAME='CommPort'		VALUE='1'/> "	
		+"<PARAM NAME='DataBits'		VALUE='8'/> "	
		+"<PARAM NAME='StopBits'		VALUE='1'/>"	
		+"<PARAM NAME='BaudRate'		VALUE='9600'/>"	
		+"<PARAM NAME='Settings'		VALUE='9600,N,8,1'/>"	
		+"<PARAM NAME='RTSEnable'		VALUE='1'/>"	
		+"<PARAM NAME='DTREnable'		VALUE='1'/>"	
		+"<PARAM NAME='Handshaking'		VALUE='0'/>"	
		+"<PARAM NAME='NullDiscard'		VALUE='0'/> "	
		+"<PARAM NAME='ParityReplace'	VALUE='?'/>"	
		+"<PARAM NAME='EOFEnable'		VALUE='0'/>"	
		+"<PARAM NAME='InputMode'		VALUE='0'/>"	
		+"<PARAM NAME='InBufferSize'	VALUE='1024'/>"	
		+"<PARAM NAME='InputLen'		VALUE='1'/>"	
		+"<PARAM NAME='OutBufferSize'	VALUE='512'/>"	
		+"<PARAM NAME='SThreshold'		VALUE='0'/>"	
		+"<PARAM NAME='RThreshold'		VALUE='1'/>"	
		+"</OBJECT>";
	
	// 将OBJECT标签添加到body中
	document.body.insertAdjacentHTML(' beforeEnd',mscomm_str);
	
	// 打开串口
	if(MSComm1.PortOpen==false){
		try{
			MSComm1.PortOpen=true;
		}catch(ex){
			alert("com1端口打开失败:"+ex.message);
		}
	}
		
	// 串口响应事件
	MSComm1.attachEvent("OnComm",function() {
		switch(MSComm1.CommEvent){
			case 2:  //接收事件
				if(mscomm_scan_value == "") {
					mscomm_scan_value = MSComm1.Input;
					// 定时读取缓存信息
					setTimeout("getMSCommScanValue()",300);
				}
				break;
			default: alert("Event Raised!"+MSComm1.CommEvent);
		}
	});
}
// 串口接收内容
var mscomm_scan_value = "";
// 读取缓存中剩余信息
function getMSCommScanValue(){
	// 读取缓存中剩余的信息
	while(MSComm1.inBufferCount > 0) {
		mscomm_scan_value += MSComm1.Input;
	}
	// 执行页面传递过来的函数
	callBackFunction(mscomm_scan_value);
	// 清空当前读取信息
	mscomm_scan_value = ""
}


test.html文件:
<html>
<head>
<title>JavaScript串口测试</title>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312" />
<script type="text/javascript" src="mscomm.js" >
</script>

<script type="text/javascript">
	var i = 0;
	function mscommCallBack(scanValue) {
		var ewtm = document.getElementById("ewtm");
		ewtm.innerHTML += "第" + (++i) + "次扫描:" + scanValue;
	}
	
	window.onload = function() {
		createMSComm(mscommCallBack);
	}
</script>
</head>

<body>

二维条码:
<div id="ewtm"></div>
</body>
</html>