2013-01-02 60 views
1

请试试我可能无法使用全局变量获取数据以外的函数。我尝试了所有我能想到的,包括window.nuTime,但没有成功。无法声明全局变量外部函数

$.ajax({ 
    cache: false, 
    type: 'POST',    
    url: 'servertime.asp', 
    data: {}, 
    success: function (data) { 
       $('#servertime').html(data); 
       window.nuTime = data; 
       //alert(data); 
       }, 
    error:  function (jxhr, msg, err) { 
       $('#response').append('<li style="color:red">' + msg + '</li>'); 
       } 
    }); 

alert(nuTime); 

回答

3

Kolink是对的!你可以这样做,这样做:

$.ajax({ 
    cache: false, 
    type: 'POST',    
    url: 'servertime.asp', 
    data: {}, 
    success: function (data) { 
        $('#servertime').html(data); 
        alertNuTime(data); 
       }, 
    error:  function (jxhr, msg, err) { 
        $('#response').append('<li style="color:red">' + msg + '</li>'); 
       } 
    }); 

function alertNuTime(data) { 
    alert(data); 
} 
+0

谢谢......我承认在这个问题上让我的大脑有点麻烦。 – hillcreative

2

当调用alert(nuTime)时,AJAX尚未返回。凡是要看结果必须是成功的处理程序中(或由上述处理机叫)

编辑:您可以实现一个“延迟”是这样的:

function someFunctionThatDependsOnAjaxBeingDone(arg1,arg2,arg3) { 
    if(typeof nuTime === "undefined") { 
     var t = this, ac = arguments.callee, arg = arguments; 
     setTimeout(function() {ac.apply(t,arg);},100); 
    } 
    else { 
     // normal function stuff here 
    } 
} 

但是这不会在一些工作除非您手动将arguments转换为数组,并且它也无法正确使用返回值。

+0

谢谢你的答案,我猜测一样多。我如何让var nuTime可用于成功处理程序之外的其他函数? – hillcreative

+0

确保其他函数在成功处理程序完成之前不会运行。 –