jQuery 时间获取扩展

本段代码实现了同步和异步获取服务器时间的放式,真正做到不会侵入服务器代码。主要原理是读取响应头部的Date值,即为服务器返回响应的时间(由服务器端生成),故可以以字符串格式取出,并可以转换为Date对象,以便后续操作。

对于获取服务器时间提供了同步和异步两种放式调用,可根据实际需要选择

复制代码
jQuery.extend({
    //获取系统时间
    getSystemTime: function(){
        return new Date();
    },
    //异步获取服务器时间
    getServerTime_async: function(success){
        $.ajax({
            data: {_:Math.random()},
            complete: function(xhr){
                var str = xhr.getResponseHeader("Date");
                var now = null;
                if(str != null)
                    now = new Date(str);
                if($.isFunction(success))
                    success(now);
            }
        });
    },
    //同步获取服务器时间
    getServerTime: function(){
        var xhr = $.ajax({
            async: false,
            data: {_:Math.random()}
        });
        var str = xhr.getResponseHeader("Date");
        if(str == null)
            return null;
        return new Date(str);
    }
});

//DEMO:
console.log("$.getSystemTime()      Result: " + $.getSystemTime());
console.log("$.getServerTime()      Result: " + $.getServerTime());
$.getServerTime_async(function(t){
    console.log("$.getServerTime_async()Result: " + t);
});
复制代码
 
原文地址:https://www.cnblogs.com/yuanxianlai/p/2707103.html