Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何根据服务器时间制作JavaScript倒计时?_Javascript_Ajax_Timer - Fatal编程技术网

如何根据服务器时间制作JavaScript倒计时?

如何根据服务器时间制作JavaScript倒计时?,javascript,ajax,timer,Javascript,Ajax,Timer,我必须做一个计时器,倒计时到一个特定的时间。我已经做过类似的事情,但是我的计时器根据客户的时间倒计时,它很容易被黑客攻击。我知道我必须进行AJAX查询,但我不知道如何将其与代码集成 我知道问题很简单,我只是在学习 // Set the date we're counting down to var countDownDate = new Date("Jan 5, 2020 15:37:25").getTime(); // Update the count down every 1 second

我必须做一个计时器,倒计时到一个特定的时间。我已经做过类似的事情,但是我的计时器根据客户的时间倒计时,它很容易被黑客攻击。我知道我必须进行AJAX查询,但我不知道如何将其与代码集成

我知道问题很简单,我只是在学习

// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2020 15:37:25").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Display the result in the element with id="demo"
  document.getElementById("clock").innerHTML = "  " + hours + ":"
  + minutes + ":" + seconds;

  // If the count down is finished, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("clock").innerHTML = " Koniec czasu!";
  }
}, 1000);
你能帮我吗

$(function () {
  $.ajax({
    type: 'GET',
    cache: false,
    url: location.href,
    complete: function (req, textStatus) {
      var dateString = req.getResponseHeader('Date');
      if (dateString.indexOf('GMT') === -1) {
        dateString += ' GMT';
      }
      var date = new Date(dateString);
      $('#serverTime').text(date);
    }
  });
  var localDate = new Date();
  $('#localTime').text(localDate);
});