JavaScipt Ajax示例(AjaxTime)

参照《JavaScript基础与实例教程》Page344

下面的,基本按照顺序贴原码了

/**
AjaxTime是一个简单的Ajax应用程序,整个应用程序共有3个程序文件:
JavaScript程序——Ajax.js
其是Ajax引擎,内含数个函数可以建立、打开、发送HTTP请求和处理响应数据
HTML文件:
HTML文件是Ajax应用程序的使用接口

服务器程序文件——PHP程序:getTime.php
*/
//建立XMLHttpRequest对象
function getHttpRequestObject(handler){
	//建立XMLHttpRequest对象
	var xmlHttpRequest=null;
	if(window.xmlHttpRequest){
		//IE7,Mozilla,Safari等浏览器
		xmlHttpRequest=new XMLHttpRequest();
	}else if(window.ActiveXObject){//IE5,IE6
		var msxmls=["MSXML2.XMLHttp.4.0",
					"MSXML2.XMLHttp.3.0",
					"MSXML2.XMLHttp",
					"Microsoft.XMLHttp"
					];
		for(i=0;i<msxmls.length;i++){
			try{//建立XMLHttpRequest对象的连接
				xmlHttpRequest=new ActiveXObject(msxmls[i]);
				break;
			}catch(e){
				return null;
			}
		}
	}
	//指定事件处理程序的名称
	httpRequest.onreadystatechange=handler;
	return xmlHttpRequest;
}
/*
*上述getHttpRequestObject()函数可以根据浏览器类型建立XMLHttpRequest
*对象,在33行指定处理响应数据事件处理程序
*/

//下方的makeRequest()函数可以打开和发送HTTP请求
function makeRequest(xmlHttpRequest,url){
	xmlHttpRequest.open("GET",url,true);//打开
	xmlHttpRequest.send(null);			//发送
}

var xmlHttp;
//发送HTTP请求来获取服务器数据
function getTime(){
	//建立XMLHttpRequest对象
	xmlHttp=getHttpRequestObject(showTime);
	if (xmlHttp!=null) {
		//建立Url网址
		var url="getTime.php";
		randNo=parseInt(Math.random()*999999);
		//新增随机数避免缓冲区问题
		url=url+"?rand="+randNo;
		makeRequest(xmlHttp,url);//建立HTTP请求
	}else{
		alert("错误!浏览器不支持XMLHttpRequest对象!")
		return;
	}
}

//下面的showTime()函数是onreadystatechange属性指定的事件处理程序
//显示时间数据
function showTime(){
	if (xmlHttp.readyState==4) {
		//获取响应
		var xmlResult=xmlHttp.responseXML;
		var myTime;
		//获取时间
		myTime=xmlResult.getElementsByTagName("now")[0];
		document.getElementById("result").innerHTML=
			myTime.childNodes[0].nodeValue;
	}
}
<?php
	header("Content-Type:text/xml");
	echo "<?xml version=\"1.0\"?>";
	$time=date("H:i:s");
	echo "<clock>";
	echo "<now>".$time."</now>";
	echo "</clock>";
?>

<html>
<head>
	<title>Ajax Time</title>
	<script type="text/javascript" src="Ajax.js"></script>
	<style type="text/css">
	.timeBox{
		width: 100px;
		background-color: #ffffff;
		border: 2px solid blue;
		padding: 10px;
	}
	</style>
</head>
<body>
	<center>
		<h2>Ajax与PHP的程序范例</h2><hr>
		<form>
			<div id="result" class="timeBox"></div><br/>
		</form>
		<input type="Button" value="获取时间" onclick="getTime()">
	</center>
</body>
</html>




你可能感兴趣的:(JavaScipt Ajax示例(AjaxTime))