如何解决此JavaScript范围问题

时间:2012-08-01 14:01:51

标签: jquery ajax

我正在尝试使用jQuery .get()方法获取文件内容,如下所示

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 个答案:

答案 0 :(得分:4)

A JAX 异步

在收到服务器的回复之前,您的最后一行会运行。

答案 1 :(得分: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);
}

答案 2 :(得分: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
});

答案 3 :(得分:1)

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

相关问题