简体   繁体   中英

Ajax isn't working on website

For my personal site I want to insert a simple ajax server clock into my website, but for some reason it's not showing up in the header. Here's the Javascript code

var httpxml;
try {
  // Firefox, Opera 8.0+, Safari
  httpxml=new XMLHttpRequest();
} catch (e) {
  // Internet Explorer
  try {
    httpxml=new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      httpxml=new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
      alert("ur browser doesn't support ajax m8, try reinstalling windows 95");
      return false;
    }
  } 
}

function stateck() {
  if(httpxml.readyState==4) {
    document.getElementById("time").innerHTML=httpxml.responseText;
  }
}

var url="ajax-server-clock-demock.php";
url=url+"?sid="+Math.random();
httpxml.onreadystatechange=stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
tt=timer_function();
}

function timer_function(){
  var refresh=1000; // Refresh rate in milli seconds
  mytime=setTimeout('AjaxFunction();',refresh)
}

And in php file

<?Php
echo date("d/m/y : H:i:s", time());
?>

Lastly in the header

<time>bacon</time>

I would have to see more code in context because several things can make this not work, in the mean time, there are multiple issues with your script, among others:

You did setTimeout(). That would only execute once, assuming you want the clock to update every second you need to use:

http://www.w3schools.com/jsref/met_win_setinterval.asp

Oh, also, you need to do something like:

document.getElementsByTagName('time')[0]; 

Instead of getElementById()

OR add an id to your element like:

<time id="mytime"></time>

And then you can call:

document.getElementById('mytime');

got it?

And also, where is declared this AjaxFunction() you are calling in setTimeout?

Also, there are much better ways to do a clock... and you should really consider using jQuery or something like that, will make your life much easier when doing AJAX, DOM manipulation and etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM