上次回复了一个帖子(忘了是哪个了)发了一个ajax push的例子,但是好像发错了,不能运行,这次发个能运行的:
以下代码,放到服务下方可运行,如tomcat。
客户端 index.html :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> ajax push </title>
</head>
<body>
ajax push test<hr>
<textarea id="ta" rows="40" cols="90"></textarea><br>
<button οnclick="test()">test</button>
<div id="inf"></div>
</body>
</html>
<script language="JavaScript">
<!--
window.$i=function(id){return document.getElementById(id); }
String.prototype.trim=function(){return this.replace(/(^\s*)|(\s*$)/g,"");}
function test()
{
$i("ta").value = "loading...\n\n";
request();
}
function request()
{
var req = createXMLHttp();
req.open("get", "push.jsp", true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
req.send(null);
req.onreadystatechange = function ()
{
if(req.readyState == 3)
{
$i("ta").value += req.responseText.trim()+"\n";
}
if(req.readyState == 4 && req.status == 200)
{
$i("ta").value += "end";
}
}
}
//创建XMLHttpRequest
function createXMLHttp()
{
if (window.ActiveXObject)
{
var arr = ["MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
for(var i=0 ; i < arr.length; i++)
{
try
{
return new ActiveXObject(arr[i]);
}catch(e){}
}
}
else if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
alert("您的浏览器不支持ajax");
return null;
}
//-->
</script>
服务端:push.jsp
<%@ page contentType="text/html;charset=utf-8"%> <% java.io.PrintWriter p=new java.io.PrintWriter(response.getOutputStream()); String msg = "a"; for(int i=0;i<10;i++) { msg+=i; p.println("HTTP/1.1 200OK"); p.println("Content-Type:text/html; charset:utf-8"); p.println("Content-Length:"+msg.length());//msg为服务器要发到客户端的信息 p.println(); p.println(msg); System.out.println(msg); p.flush(); response.getOutputStream().flush(); try { Thread.sleep(1000); } catch(Exception e) { } } %>