【问题标题】:jQuery variable becomes undefined for no reasonjQuery变量无缘无故变得未定义
【发布时间】:2012-02-27 20:01:56
【问题描述】:

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

var foo;

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

alert(foo);

问题显然是,在 jQuery 函数结束后,变量变得未定义(即使它被声明为 在该范围之外)。第一个alert(foo) 可以正常显示文件的内容,但第二个什么也不显示。

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

【问题讨论】:

    标签: javascript jquery variables scope undefined


    【解决方案1】:

    试试

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

    【讨论】:

    • 不走运:/ 仍然返回“未定义”
    【解决方案2】:

    这就是异步编程的工作原理$.get 函数在调用回调处理程序时“结束”,而不是按照代码以线性方式结束。

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

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

    您的代码中的一些 cmets,希望您能更好地理解:

    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
    

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

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

    【讨论】:

    • 好的,但是我怎样才能将我在$.get处理程序中获得的数据保存在外部的变量中?
    • 你不能“保存”它以备后用,除非你做一个不推荐的同步调用。回调是您“继续”运行代码的地方。您现在不妨开始了解异步编程,因为稍后您将使用很多它:)
    • 是的,我想我明白了,虽然我习惯了“线性”编程,但这很尴尬。我将所有代码(操作文本文件的内容)放在 $.get 中,它就可以工作了!所以谢谢男人
    猜你喜欢
    • 2017-08-08
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多