문제

I'm trying to modify this http://www.w3schools.com/php/php_ajax_database.asp

I'm just using the HTML part of that ^. My php file only have

<?php
echo rand();
?>

And it works fine! It updates every time I switch something on the drop-down list. But, I want it to run every second, but it won't work. This is what my HTML looks like:

<html>
<head>
<script>
function showUser() {
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","ajax/test.php?q="+str,true);
  xmlhttp.send();
}
setInterval(showUser, 1000);
</script>
</head>
<body>

<div id="txtHint"><b>this will be updated</b></div>

</body>
</html>

The SetInterval won't run it. The php file is still only echo rand();. It worked at some point but I screwed something up I believe. Thanks in advance.

도움이 되었습니까?

해결책

setInterval() is likely running just fine, but showUser() is ending with an error since str is not defined. Check your JavaScript console for errors.

Either remove the reference to str, or define it somewhere.

다른 팁

try this:

 setInterval(function(){showUser()}, 1000);

Replace

setInterval(showUser, 1000);

with

window.onload = function() {
    setInterval(showUser, 1000);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top