在函数之间传递变量

时间:2011-01-24 21:35:00

标签: javascript jquery

我有两个函数,一个在用户加载页面时发出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);
}

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分: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的优点。此代码未经测试。