2014-02-14 18 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')); 
     } 
    }); 

}