ajax模拟comet

模拟服务器推送数据,不多说了 看看我写的代码很容易明白 写的不好的请多多指教
servlet:
package com;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ajaxServlet extends HttpServlet{
 private static final String CONTENT_TYPE="text/xml; charset=gb2312";
 public void init() throws ServletException{
 }
 public void doGet(HttpServletRequest request,HttpServletResponse response)
   throws ServletException,IOException{
     response.setContentType(CONTENT_TYPE);
     System.out.println(request.getParameter("a"));
     try {
			int i = 0;
			while (true) {

				System.out.println(i);


				if(i>3){
					PrintWriter out=response.getWriter();
					StringBuffer sb = new StringBuffer("<type>");
					sb.append("<type_name>" + i + "</type_name>");
					sb.append("</type>");
					out.write(sb.toString());
					out.close();

					i=0;
					break;
				}
				i++;
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
				}
			}
		} catch (Exception e) {
		}
 }
}

jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<head>
<title>AJAX.html</title>
</head>
<script type="text/javascript">

function getResult(){
var current_time = new Date();
current_time=Math.round(Math.random()*10000);
alert(current_time);
  var url = "/ajaxtest/ajaxServlet?a="+current_time;
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  }else if (window.ActiveXObject){
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if(req){
     req.open("GET",url, true);
     req.onreadystatechange = complete;
     req.send(null);
  }
}

function aaa(){
	getResult();
}
function complete(){
  if (req.readyState == 4){
     if (req.status == 200) {
       var type = req.responseXML.getElementsByTagName("type_name");
       var str=new Array();
       for(var i=0;i< type.length;i++){
         str[i]=type[i].firstChild.data;
         document.all['td'].innerHTML+=str[i]+"";
       }
       aaa();
   }
 }
}

</script>
<body>
<table width="80%" border="0" cellspacing="0" cellpadding="0">
<input type="button" value="aaa" onclick="getResult()"/>
<tr><td id="td">&nbsp;</td></tr>

</table>

</body>

你可能感兴趣的:(java,Ajax,servlet,Microsoft,Comet)