php+ajax简单应用

ajax_functions.js文件

ajax_functions.js
// 创建XMLHTTPRequesst对象
function getXMLHTTPRequest(){
var req = false;
try{
//对于火狐浏览器
req = new XMLHttpRequest();
}
catch(err){
try{
//对于IE浏览器
req = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(err){
try{
//对于IE的其他版本
req = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(err){
req
= false;
}
}
}
return req;
}

//时间发生时执行的函数
function getServerTime(){
var thePage = 'servertime.php';
myRand
= parseInt(Math.random()*9999999999999);
var theUrl = thePage + "?rand=" + myRand;
myReq.open(
"GET", theUrl, true);
myReq.onreadystatechange
= theHTTPResponse;
myReq.send(
null);
}

//HTTP状态改变函数
function theHTTPResponse(){
if(myReq.readyState == 4){
if(myReq.status == 200){
var timeString = myReq.responseXML.getElementsByTagName('timestring')[0];
document.getElementById(
'showtime').innerHTML = timeString.childNodes[0].nodeValue;
}
}
else{
document.getElementById(
'showtime').innerHTML = '<img src="ajax-loader.gif" />';
}
}

前台页面ajaxservertime.html

 

ajaxservertime.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" />
<style>
body
{
background
: #fff;
font-family
:Verdana, Geneva, sans-serif;
font-size
: 12pt;
font-weight
: normal;
}

.displaybox
{
width
: 300px;
height
: 70px;
background-color
:#fff;
border
: 2px solid #000;
line-height
: 2.5em;
margin-top
:25px;
font-size
: 12pt;
font-weight
: bold;
}
</style>
<script type="text/javascript" src="ajax_functions.js"></script>
<script type="text/javascript">
var myReq = getXMLHTTPRequest();
</script>
<title>ajax获取服务器时间</title>
</head>
<body>
<div align="center">
<h1>Ajax Demonstration</h1>
<p align="center">将鼠标移动到下面的盒子,就可以获取服务器的时间了<br />
当前页面不会刷新,只有盒子的内容会改变
</p>
<div id="showtime" class="displaybox" onmouseover="javascript:getServerTime();"></div>
</div>
</body>
</html>

 

 

servertime.php获取服务器时间,以xml格式返回

<?php
date_default_timezone_set('PRC');
header('Content-type: text/xml');
echo "<?xml version=\"1.0\" ?>
<clock>
<timestring>It is
".date('H:i:s')." on ".date('M d, Y').".</timestring>
</clock>
";
?>

 

posted @ 2010-11-05 11:57  nodot  阅读(332)  评论(0)    收藏  举报