Ajax计数器

这几天刚接触Ajax,写了一个非常简单的计数器。
客户端文件counter.htm用作模板,counter.php调用counter.htm模板。
当访问counter.php时,数据库记录ip、time,计数器加一。
XMLHttpRequest向counter_action.php发出请求,counter_action.php返回一个数字。
函数setTimeout()设置自动更新时间。

counter.htm清单

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"
>
< html >
< head >
< meta  http-equiv ="Content-Type"  content ="text/html; charset=gb2312" >
< title > Ajax计数器 </ title >
< style  type ="text/css" >
<!--
.style2 
{
    font-size
: 16px;
    color
: red;
}

-->
</ style >
< script  type ="text/javascript" >
var xmlHttp;
function createXMLHttpRequest()
{
    
if (window.ActiveXObject)
    
{
        xmlHttp 
= new ActiveXObject("Microsoft.XMLHTTP");
    }
 
    
else if (window.XMLHttpRequest)
    
{
        xmlHttp 
= new XMLHttpRequest();
    }

}


function doCount()
{
    createXMLHttpRequest();    
    
var url = "counter_action.php";
    xmlHttp.onreadystatechange 
= handleStateChange;
    xmlHttp.open(
"GET", url, true);
    xmlHttp.send(
null);
}


function handleStateChange()
{
    
if(xmlHttp.readyState == 4)
    
{
        
if(xmlHttp.status == 200)
        
{
            
var counter = document.getElementById("counter");
            counter.innerHTML 
= xmlHttp.responseText+"";
            setTimeout(
"doCount()",10000);
        }

    }

}

</ script >
</ head >
< body  onLoad ="doCount()" >
< align ="center"  class ="style2" > Ajax计数器 </ p >
< table  width ="300"  border ="0"  align ="center" >
  
< tr >
    
< td >< div  align ="center"  id  ="counter" ></ div ></ td >
  
</ tr >
</ table >
</ body >
</ html >

counter.php清单

<? php
include_once ( " ./config/connect.php " );
include_once ( " ./private/functions.php " );

$ip   =  getip();  // 获取ip,函数定义在functions.php中
$time   =   time ();

// 访问数据库
$sql   =   " INSERT INTO `counter` VALUES (NULL,'$ip', '$time') " ;
$rs   =   $conn -> Execute( $sql );


// 解析模板
$tpl -> set_file( " file " , " templates/counter.htm " );
$tpl -> parse( " main " , " file " );
$tpl -> p( " main " );

@
$rs -> Close();
@
$conn -> Close();
?>

counter_action.php清单

<? php
include_once ( " ./config/connect.php " );
include_once ( " ./private/functions.php " );

// 访问数据库
$sql   =   " SELECT * FROM `counter` " ;
$rs   =   $conn -> Execute( $sql );
$counter   =   $rs -> rowcount();
$counter ++ ;
echo   $counter ;

// 释放数据库句柄
@ $rs -> Close();
@
$conn -> Close();
?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值