这个Ajax / Javascript代码有什么问题?

时间:2013-02-13 05:40:35

标签: php javascript ajax

我正在尝试执行一个功能,它会在点击按钮时显示时钟,但我无法显示时钟。我对这些东西有点新意,非常感谢对此的一些帮助,也解释了我做错了什么。

提前致谢!

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script>

function getXMLHTTPRequest() {
try {
req = new XMLHTTPRequest();
} catch(err1) {
    try {
    req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (err2) {
        try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (err3) {
            req = false;
        }
    }
}
return req; 
}

var http = getXMLHTTPRequest();

function getServerTime() {
    var myurl = 'telltimeXML.php';
myRand = parseInt(Math.random()*9999999999999);
var modurl = myurl+"?rand="+myRand;
http.open("GET", modurl, true);
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>

<title>Ajax</title>
<style>
.displaybox {
width:150px;
background: #ffffff;
border:2px solid #000;
padding:10px;
font:24px normal verdana, helvetica, arial, sans-serif;
margin: 0 auto;
}
</style>
</head>

<body style="background-color:#cccccc; text-align:center">
<h1>Ajax</h1>
<h2>Hamta tiden fran servern utan att uppdatera sidan</h2>
<form>
<input type="button" value="Hamta tiden fran servern" />
</form>
<div id="showtime" class="displaybox"></div>
</body>
</html>

这是.PHP代码..(telltimeXML.php)

<?php
header('Content-Type: text/xml');
echo "<?xml version=\"1.0\" ?><clock1><timenow>"
.date('H:i:s)."</timenow></clock1>";
?>

2 个答案:

答案 0 :(得分:0)

你错过了在telltime XML.php文件中关闭日期函数中的'。更换此内容:

 header('Content-Type: text/xml');
 echo "<?xml version=\"1.0\" ?><clock1><timenow>".date('H:i:s)."</timenow></clock1>";

 header('Content-Type: text/xml');
 echo "<?xml version=\"1.0\" ?><clock1><timenow>".date('H:i:s')."</timenow></clock1>";

答案 1 :(得分:0)

我认为你在这一行的末尾遗漏了一些括号:

http.onreadystatechange = useHttpResponse;