1.prepare front-end code, meta content-type cannot be ignored! as to the xhr, status should be 3
<!doctype html>
</html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="d"></div>
<script type="text/javascript" src="/dwztp/Public/dwz/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var xhr=new XMLHttpRequest(),pos=0;
xhr.onreadystatechange=function(){
if(xhr.readyState==3){
$("#d").html(xhr.responseText.substr(pos));
pos= xhr.responseText.length;
}
else{
$("#d").html(xhr.responseText);
}
};
$.ajaxSetup({cache:false});
xhr.open("get","a.php",true);
xhr.send(null);
// $.get("a.php",function(data){
// //document.write(data);
// });
</script>
</body>
</html>
2.back-end, remember to to call two methods to set time limit to unlimited and cache-control to be no-cache;
<?
set_time_limit(0);
header("Cache-Control: no-cache, must-revalidate");
echo(date(‘Y‘));
$no=0;
while (date(‘Y‘) == ‘2016‘){
echo ‘hello 2016+‘.$no.‘<br/>‘;
ob_flush();
flush();
sleep(2);
$no++;
}
?>
comet realization with ajax&php
原文:http://www.cnblogs.com/hualiu0/p/5149640.html