2012-08-01 37 views
0

我试图让使用jQuery .get()方法的文件内容类似下面如何解决这个JavaScript作用域的问题

var news; 
$.get('news.txt', function (dat) { 
    news = dat; 
    if ($('#removeN').is(':checked')) { 
     news = ""; 
    } 
    alert(news) // Displaying exact result;    
}); 
alert(news) // Displaying undefined..; Why? 

有人请澄清我的疑问。

+4

欢迎** **异步的奇妙世界!你不能那样做。 – SLaks 2012-08-01 14:02:24

+1

改为拨打同步电话? – Pheonix 2012-08-01 14:02:59

+3

@Pheonix:不;别。 – SLaks 2012-08-01 14:03:09

回答

4

A JAX是异步

您的最后一行在您收到服务器响应之前运行。如果你想要做的事与新闻

3
var news; 
$.get('news.txt', function (dat) { 
    news = dat; 
    if ($('#removeN').is(':checked')) { 
     news = ""; 
    } 
    alert(news) // BEFORE THIS!   
}); 
alert(news) // THIS EXECUTES 

用这个代替:

$.get('news.txt', function (dat) { 
    news = dat; 
    if ($('#removeN').is(':checked')) { 
     news = ""; 
    } 
    doSomething(news) // Displaying exact result;    
}); 

var doSomething = function(data) { 
    alert(data); 
} 
+0

我仍然面临同样的问题... – Exception 2012-08-01 15:31:41

1

的第二个参数$不用彷徨是回调。基本上,$ .get所做的是为内容加载的事件设置一个事件处理程序,并说“这是我在此事件触发时要运行的函数”。就像其他人所说的那样,它还没有解雇那个事件,所以代码遍历并找到你的未初始化的变量。

2

你也应该能够分离出担忧..

var news; 
$.get('news.txt', function (dat) { 
    //process news  
}).done(function(dat){ 
    //display news, or maybe more processing related to this particular function block 
    alert(news); 
}).fail(function(){ 
    //oops, something happened in attempting to get the news. 
    alert("failed to get the news"); 
}).always(function(){ 
    //this eventually gets called regardless of outcome 
});