1,文件 index.php
<!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>页面局部刷新_www.jb200.com</title> </head> <script type="text/javascript" src="fun.js"></script> <script type="text/javascript" src="jquery-1.7.2.min.js"></script> <body> <div id="test1">用户 GM</div> <div>未读消息(<span id="count" ></span>)条</div> </body> </html>
2,文件 fun.js,注意empty判断。
<script> /** * 局部刷新js代码 * edit www.jb200.com */ function historyLotteryCode_1(){ $.ajax({ type: 'POST', url : 'ajaxReturn.php', data: "userid=12", success: function(data){ alert(data); var partn = /<script.*>.*</script>/; if( data == 'empty' && partn.test(data) ){return;} eval_r("data="+data); document.getElementByIdx_x("count").innerHTML=data.count; setTimeout(historyLotteryCode_1,5000); } }); } setTimeout(historyLotteryCode_1,5000); </script>
3,文件 ajaxReturn.php
<?php $id=$_POST["userid"]; $info = array('count'=>'1', 'user'=>'xiao', 'ai'=>$id); $userinfo = json_encode($info); echo $userinfo; ?>
说明:
因为用到了jquery,所以以上代码中不要忘记引入正确的jquery框架代码。