日期:2014-05-17  浏览次数:20609 次

使用htmlfile隐藏IE浏览器正在打开网页状态的代码

一般情况下,采用长连接,能持续的在客户端显示信息
比如

?
<%@ page language="java" c pageEncoding="utf-8"%>
<%
  out.flush();
  int number = 0;
  while (true) {
    out.println(new java.util.Date()+"
");
    out.flush();
    Thread.sleep(100);
    System.out.print(".");
    if (number++ > 100) {
      break;
    }
  }
%>

这个代码会在客户端连续的显示时间。请注意,浏览器的正在下载是一直在运行中的。这个会让客户感到疑惑,难道还有东西在运行吗?


下面的这个方法,可以解决这个问题

我们先看服务器端代码。
使用了prototype.js

?
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Comet php backend</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<script type="text/javascript">
  // KHTML browser don't share javascripts between iframes
  var is_khtml = navigator.appName.match("Konqueror") || navigator.appVersion.match("KHTML");
  if (is_khtml)
  {
    var prototypejs = document.createElement('script');
    prototypejs.setAttribute('type','text/javascript');
    prototypejs.setAttribute('src','../js/prototype.js');
    var head = document.getElementsByTagName('head');
    head[0].appendChild(prototypejs);
  }
  // load the comet object
  var comet = window.parent.comet;
</script>
<%
  out.flush();
  int number = 0;
  while (true) {
    // 这里生成了调用js的代码
    out.println("<script type='text/javascript'>comet.printServerTime('" + new java.util.Date() + "');</script>");
    out.flush();
    Thread.sleep(100);
    // 控制台显示,程序正在运行,正式运行可去掉
    System.out.print(".");
    // 防止程序一直运行,给调试带来麻烦,正式运行可去掉
    if (number++ > 100) {
      break;
    }
  }
%>

关键在客户端代码

查看复制到剪切板打印
 
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Comet demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="../js/prototype.js"></script>
</head>
<body>
<div id="content">The server time will be shown here</div>
<script type="text/javascript">
var url= 'testLinkData2.jsp';
var comet = {
  connection   : false,
  iframediv    : false,
  
  initialize: function() {
    if (navigator.appVersion.indexOf("MSIE") != -1) {
    
      // For IE browsers
      comet.connection = new ActiveXObject("htmlfile");
      comet.connection.open();
      comet.connection.write("<html>");
      comet.connection.write("<script>document.domain = '"+document.domain+"'");
      comet.connection.write("</html>");
      comet.connection.close();
      comet.iframediv = comet.connection.createElement("div");
      comet.connection.appendChild(comet.iframediv);
      comet.connection.parentWindow.comet = comet;
      comet.iframediv.innerHTML = "<iframe id='comet_iframe' sr