jQuery变量无缘无故变得不确定

fed*_*o-t 0 javascript variables jquery scope undefined

我有以下代码,其中我想bar.txt在变量中保存文件的内容foo:

var foo;

jQuery.get('http://example.com/bar.txt', function(data) {
     foo = data;
     alert(foo);
});        

alert(foo);
Run Code Online (Sandbox Code Playgroud)

问题是,显然,在jQuery函数结束后变量变为未定义(即使它该范围之外声明).第一个alert(foo)正确显示文件的内容,但第二个没有显示任何内容.

谁能告诉我这里发生了什么?

Dav*_*ing 7

这就是异步编程的工作原理.的$.get功能"结束"时,回调处理程序是通过以下的代码调用,而不是以线性方式.

alert()运行此代码时将触发的"第一个" 是您在最后一行($.get处理程序外部)调用的那个,到那时ajax请求尚未完成.

第二个alert将在ajax完成时(在$.get处理程序内)发生,并将显示您分配给变量的数据,来自handler参数.

对您的代码有一些评论,希望您能更好地理解:

var foo; // foo is now undefined

jQuery.get('http://example.com/bar.txt', function(data) {
     // the code in this handler will be executed after the ajax is complete
     foo = data;
     alert(foo); // foo is now the contents of bar.txt, this will happen last
});        

alert(foo); // foo is still undefined, and this alert happens first
Run Code Online (Sandbox Code Playgroud)

如果需要一个关于如何"重用"foo变量的示例,可以对此进行不同的编程:

var foo;

jQuery.get('http://example.com/bar.txt', function(data) {
     foo = data;
     onData();
});        

function onData() {
    alert(foo);
}
Run Code Online (Sandbox Code Playgroud)