Javascript和Ajax - 无法传输可变内容

时间:2014-02-14 16:03:01

标签: javascript ajax variables

我目前正在使用以下代码进行一些测试:

function updateCurrentTime() {
    var HeaderDate;

    $.ajax('/', {
        url: "http://www.google.com",
        type: 'HEAD',
        success: function(r,status,xhr) {
            HeaderDate = xhr.getResponseHeader('Date');
        }
    });
    var curTime = new Date(HeaderDate);
}

不幸的是在以下一行:

var curTime = new Date(HeaderDate);

我无法在AJAX代码中检索HeaderDate的变量内容。

目标是从与运行脚本的本地计算机不同的位置获取时间。

我甚至尝试使用全局变量而没有任何成功。

你可以帮帮我吗?

非常感谢你的时间和帮助。

1 个答案:

答案 0 :(得分:0)

这是因为在{ajax返回之前设置curtime

以下内容会更好,但这里要说的是,当ajax返回时,您需要更新应用程序,因此在success回调中。

function updateCurrentTime() {
    var HeaderDate, curTime;
    function setCurrentTime(time){ curTime = new Date(time);}

    $.ajax('/', {
        url: "http://www.google.com",
        type: 'HEAD',
        success: function(r,status,xhr) {
            setCurrentTime(xhr.getResponseHeader('Date'));
        }
    });

}