我一直在關注一個我一直在閱讀的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