2014-02-10 47 views
1

由于某种原因,get函数中的newdata在尝试在函数外部使用时丢失了。该警报显示0,但是当我将警报放在get函数中时,它显示80(它应该是什么)。任何想法?失去jquery以外的变量获取

var newdata = 0; 
//Get latest stat from file 
$.get("http://localhost/?stat=size", function(data) { 
    //Strip any letters from result (if any) 
    newdata = data.replace(/\D/g,''); 
    //alert("Load was performed."+newdata); 
}); 
alert("Load was performed."+newdata); 

感谢

+0

,看一下http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call –

+0

http://stackoverflow.com/questions/ 14220321 /如何返回答案从一个AJAX调用 –

回答

0

您的变量没有迷路,jQuery的获得是一个异步请求。这意味着当你提醒你还没有得到你的数据,所以它仍然会返回0.

你可以改变你的代码同步运行,这将解决你的问题,但你应该小心,因为它会阻止任何更多的代码执行直到你得到你的回应。

$.ajax({ 
     url: 'http://localhost/?stat=size', 

     success: function(data) { 
         newdata = data.replace(/\D/g,''); 
        }, 
     async: false 
    });  

不过我建议只运行你需要在你走向成功里面做什么都,这意味着在您检索数据并不会阻止任何其他执行它将只运行。

var newdata = 0; 
//Get latest stat from file 
$.get("http://localhost/?stat=size", function(data) { 
    //Strip any letters from result (if any) 
    newdata = data.replace(/\D/g,''); 
alert("Load was performed."+newdata); 
}); 
+0

这将工作正常,没关系,如果它停止其他代码,其基于时间。 (我将函数(结果)更新为函数(数据)。非常感谢您的帮助。 – deejuk