2011-01-24 123 views
0

我有兩個函數,一個是在用戶加載頁面時發出Ajax請求,另一個是每5秒鐘左右運行一次以更新內容。使用第一個函數,我可以輸出一個我需要在第二個函數中使用的變量。在函數之間傳遞變量

function insert_last_ten() { 
    $.ajax({ 
     url: 'freeshout/chatlog.php', 
     success: function(data) { 
     $("#inner-wrap").html(data); 
     var first_child = $("#inner-wrap :first-child").html(); 
     var value = first_child.match(/(value)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/); 
     var realtime = value[2]; 
     } 
    }); 
    } 

基本上,我需要使用realtime來做另一個功能的其他功能。爲了簡單起見,我們假設這是第二個功能:

function update() { 
    alert(realtime); 
} 

我該怎麼去做這項工作?

+0

你可以將`realtime`移動到更公開的範圍嗎? – jocull 2011-01-24 21:38:15

+0

讓`realtime`成爲一個全局變量將是簡單的方法。 – 2011-01-24 21:39:00

回答

2

success回調中,取消超時並使用更新的值啓動一個新的超時。您可以通過參數超時標識傳遞給insert_last_tensuccess回調將它撿起來通過關閉:

function createUpdateTimer(value, interval) { 
    return setTimout(
     function() { 
     alert(value); // The created function knows what value is due to closure 
     }, interval); 
} 

function insert_last_ten(timer) { 
    $.ajax({ 
     url: 'freeshout/chatlog.php', 
     success: function(data) { 
      $("#inner-wrap").html(data); 
      var first_child = $("#inner-wrap :first-child").html(); 
      var value = first_child.match(/(value)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/); 
      var realtime = value[2]; 
      cancelTimer(timer); // This callbac knows what timer is due to closure 
      timer = createUpdateTimer(realtime, 500); 
     } 
    }); 
} 

// Start the timer: 
var timer = createUpdateTimer('initial value', 500); 

// Make ajax request: 
insert_last_ten(timer); 

請注意,我只是剛剛開始使用JavaScript的好的部分熟悉自己。此代碼未經測試。