我一直在关注一个我一直在阅读的Ajax书籍中的例子。Ajax拒绝提取服务器时间
我按照指示将代码放在一起。这个想法是获取php服务器的时间,并在单击按钮时显示它。
该出版物是2006年,我不确定我写的任何内容是否过时,或许不再支持,导致它被打破?
我会很感激任何指导,谢谢!
AJAX页面
<!DOCTYPE html>
<html>
<head>
<title>Ajax Demonstration</title>
<style>
.displaybox{
width: 150px;
margin:0 auto;
background-color: #fff;
border: 2px solid #000;
padding: 10px;
font:24px normal verdana, helvetica, arial, sans-serif;
}
</style>
<script language="JavaScript" type="text/javascript">
function getXMLHTTPRequest(){
try{
reg = new XMLHttpRequest();
}
catch(err1){
try{
req = new ActiveXObject("Msxm12.XMLHTTP");
}
catch(err2){
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(err3){
req = false;
}
}
}
}
var http = getXMLHTTPRequest();
function getServerTime(){
var myurl = 'telltimeXML.php';
myRand = parseInt(Math.random()* 999999999999999);
//add random number to URL to avoid cache problems
var modurl = myurl+"?rand="+myRand;
http.open("GET", modurl, true);
//set up the callback function
http.onreadystatechange = useHttpResponse;
http.send(null);
}
function useHttpResponse(){
if(http.readyState == 4){
if(http.status == 200){
var timeValue = http.responseXML.getElementsByTagName("timenow")[0];
document.getElementById('showtime').innerHTML = timeValue.childNodes[0].nodeValue;
}
}
else{
document.getElementById('showtime').innerHTML = '<img src="anim.gif">';
}
}
</script>
</head>
<body style="background-color:#ccc; text-align:center" onLoad="getServerTime()">
<h1>Ajax Demonstration</h1>
<h2>Getting the server time without page refresh</h2>
<form>
<input type="button" value="Get Server Time" onClick="getServerTime()" />
</form>
<div id="showtime" class="displaybox"></div>
</body>
PHP页面
<?php
header('Content-Type: text/xml');
echo "<?xml version='1.0' ?><clock1><timenow>".date('H:i:s')."</timenow></clock1>";
?>
检查浏览器的开发工具是否有错误 - 尤其是“Consol e“和”网络“。另外,这两个文件是通过HTTP/HTTPS在相同的目录路径中提供的吗? – 2013-03-24 00:42:51
为简单起见,所有文件都在同一个目录中。这是控制台正在记录的错误> Uncaught TypeError:无法调用未定义的方法'open' – sark9012 2013-03-24 00:50:28