I am trying to make a simple AJAX program, that always displays the newest text from a file.
It should be retrieving it from the file, wait 2 seconds, and if something changed, write it out.
I tried already but the code doesn’t seem to work.
<html>
<head>
<script type="text/javascript">
function sleep()
{
var dt = new Date();
dt.setTime(dt.getTime() + 2000);
while (new Date().getTime() < dt.getTime());
}
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxtest.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<script>
while (0=0)
{
loadXMLDoc();
</script>
<div id="myDiv"><h2>Status</h2></div>
<script type="text/javascript">
setTimeout(loadXMLDoc(),1000)
}
</script>
</body>
</html>
How do I get it to check and update the text automatically?
Thanks!
Edit:
Here is the final code for anybody who is interested:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","status.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<script type="text/javascript">
loadXMLDoc();
</script>
<div id="myDiv">Current Status</div>
<script type="text/javascript">
setInterval("loadXMLDoc()", 2000);
</script>
</body>
</html>
I am not sure if its a typo or a thing from another language. (Like PHP)
In HTML you cannot have javascript code that goes across multiple script tags.
Also your while loop has only one = sign, would need two to be comparison.
But that being said you do want setTimeout or setInterval, because non multi-threaded javascript will just lockup, mulit-threaded ones would wasting processing time as well but not totally lockedup.
Something like
setTimeout executes the first parameter as javascript after the second parameter of milliseconds.
setInterval executes the like setTimeout except every X milliseconds.
Both setTimeout and setInterval return a value which can be used to stop the javascript from being executed again.
That value is used in
clearTimeout(value)orclearInterval(value)The body of your page would look like this: