日期:2014-05-16 浏览次数:20344 次
??? 这几天在做一个Web监测系统,需要对多个Server进行监测,采用的做法就是把需要监测的Server在页面上显示出来,然后通过Ajax对各个Server进行异步监测,开始的时候,针对每个Server,我都采用同一个JS方法循环和后台进行异步通信,结果程序一跑,发现根本不能做到同时异步监测多个Server,因此我想到了在Web页面Load的时候,根据后台返回的Server的个数,动态为每个Server创建不同的JS函数来处理异步通信请求。这样就可以做到同时异步监测多个Server。代码如下:
?
Html代码,被监测的Server列表:
<body onload="initializeMethod()"> <table width="500"> <tr> <td width="100%"> <table width="500" id="serverTab" border="1" cellpadding="0" cellspacing="0" align="left"> <tr bgcolor="#0099CC"> <td width="30%"><div align="center"> Host</div></td> <td width="15%"><div align="center"> Port</div></td> <td width="15%"><div align="center"> Interval(s)</div></td> <td width="35%"><div align="center"> Comment</div></td> </tr> <s:iterator value="serverListByType" id="serverList" > <tr> <td><div align="left"><s:property value="host" /> </div></td> <td><div align="left"><s:property value="port" /></div></td> <td><div align="left"><s:property value="interval" /></div></td> <td><div align="left"><s:property value="comment" /> </div></td> </tr> <br /> </s:iterator> </table> </td> </tr> </table> </body>
?JS代码,动态生成异步监测函数:
<script type="text/javascript"> var functionArray = new Array(); function initializeMethod(){ var serverTab=document.getElementById("serverTab"); for(var i = 1; i<=serverTab.rows.length-1; i++) { functionArray[i] = function(rowId){ var xmlHttp ; if(window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest; } else if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } else { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } var tab=document.getElementById("serverTab"); var cbx = document.getElementsByName("server_id"); var interval = 0; var first=true; //tab.rows[rowId].bgColor='FFFFFF '; //var minInterval = tab.rows[1].cells[3].children[0].value ; var ServerLists=""; for(var j=0;j<tab.rows[rowId].cells.length;j++) { for(var z=0;z<tab.rows[rowId].cells[j].children.length;z++) { var cb= tab.rows[rowId].cells[j].children[z]; ServerLists+=cb.innerText; ServerLists+=","; } } ServerLists+="\n"; var url = "startMonitor"; var param = "serverList="+ServerLists; xmlHttp.open("post",url,true); xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlHttp.onreadyStatechange=function(){ if(xmlHttp.readyState==4) { if( xmlHttp.status == 200 ){ setInterval("functionArray["+rowId+"]("+rowId+")",interval); if(xmlHttp.responseText == 0) { tab.rows[rowId].bgColor='#FF0000 '; }else {