2014-02-14 17 views
-1

我使用下面的代码目前正在做一些测试:JavaScript和Ajax - 无法传递变量的内容

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的可变内容。

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

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

你能帮我一下吗?

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

回答

0

这是因为curtime设置了ajax返回之前。

像下面这样的东西会更好,但这里的东西就是你需要让你的应用程序在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')); 
     } 
    }); 

}