ajax只工作一次

时间:2011-05-22 06:53:39

标签: php ajax

我想将我的网站转换为ajax,所以我一直在玩它。我写了一个简单的HTML页面和PHP脚本,但是当我运行它时,我不断回到原点。我确信我错过了一些简单但却无法解决的问题。

PHP

<?php
echo date("Y.m.d H:i:s", $_SERVER['REQUEST_TIME']);
?>

HTML

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>Untitled Document</title>
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
var ajaxRequest;  // The variable that makes Ajax possible!

try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e){
    // Internet Explorer Browsers
    try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
            // Something went wrong
            alert("Your browser broke!");
            return false;
        }
    }
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
        document.myForm.time.value = ajaxRequest.responseText;
    }
}
ajaxRequest.open("POST", "serverTime.php", true);
ajaxRequest.send(null); 
}
//-->
</script>
</head>
<body>
<form name='myForm'>
Name: <input type='text'  name='username' /> <br />
Time: <input type='text' name='time' />
    <input type="button" onclick="ajaxFunction();" value="here">
</form> 
</body>
</html>

每次点击按钮,我都会回来。这让我觉得我只和服务器说过一次。我希望能够每秒点击一次按钮,看看时间的变化。我每次都需要某种代码来重置我的请求吗?

提前感谢您的帮助。在我继续前进之前,我需要了解这一点。

3 个答案:

答案 0 :(得分:2)

浏览器可以缓存响应。一个简单的hacky解决方案是将随机get参数附加到url,例如var url = "http://www.example.com/?rand=" + Math.random();

答案 1 :(得分:0)

您正在使用$ _SERVER ['REQUEST_TIME'],它返回初始请求的时间。您需要使用time()或完全省略该参数。

答案 2 :(得分:0)

移动ajaxRequest.open(“POST”,“serverTime.php”,true);在ajaxRequest.onreadystatechange = function()之前。

这是ajax订单

开() 的onreadystatechange 发送()