开发者

ajax only working once

I am wanting to convert my website to ajax so I have been playing with it. I wrote a simple HTML page and PHP script but when I run it I keep getting the same time back. I am sure I am missing something simple but cant figure it out.

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>

Every time I click the button I get the same time back. This makes me think that I am only talking to the server once. I want to be able to click the button every second and see the time change. Do I need some kind of code to reset my request each time?

Thanks in advance for any help. I need to understand this before I can move forward.


Responses may be cached by the browser. A simple hacky solution is to append a random get parameter to the url, e.g. var url = "http://www.example.com/?rand=" + Math.random();


You're using $_SERVER['REQUEST_TIME'] which returns the time of the initial request. You need to use either time() or omit that parameter altogether.


move the ajaxRequest.open("POST", "serverTime.php", true); before ajaxRequest.onreadystatechange = function() line.

here is the ajax order

open() onreadystatechange send()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜