为什么我不能传递服务器的日期时间到我的本地jquery脚本

Why I cannot pass the datetime of the server to my local jquery script?

本文关键字:我的 脚本 jquery 时间 日期 不能 服务器 为什么      更新时间:2023-09-26

我有一个非常简单的timeoftheserver.php页面:

<?php
   echo date('D, d M y H:i:s');
?>

和我的本地脚本也很简单:

var today;
try {
  today = new Date($.ajax({'type': 'HEAD', 'url': 'timeoftheserver.php'}).getResponseHeader('Date'));
}
catch(err) {
  today = new Date();
  alert("here");
}
alert(today);

但不是服务器时间(甚至是本地时间和警报here),我得到了弹出窗口:

Thu Jan 01 1970 01:00:00 GMT+0100 (Central Europe Standard Time)

这段代码有什么问题?

您正在使用head请求,它不包括响应体。将"head"改为"GET"

否则,你可以在报头中包含时间,并从那里获取它,而不是在正文中发送它。

方法1)使用头文件:

在PHP中发送时间作为标头,将PHP更改为:

header("x-app-date: ".date('D, d M y H:i:s'));

然后像这样在AJAX中获取日期…

$.ajax({
    'type': 'HEAD', 
    'url':'timeoftheserver.php',
    'complete': function(r){
         today = new Date(this.getResponseHeader('x-app-date'));
     }
});
方法2:使用Body

让PHP保持原样。将Ajax更改为:

$.ajax({
    'type': 'GET', 
    'url': 'timeoftheserver.php',
    'complete': function(resp){
        today = new Date(resp);
    }
});