javascript - jQuery variable becomes undefined for no reason - Stack Overflow

I have the following code, in which I want to save the content of the file bar.txt in the variable foo:

I have the following code, in which I want to save the content of the file bar.txt in the variable foo:

var foo;

jQuery.get('.txt', function(data) {
     foo = data;
     alert(foo);
});        

alert(foo);

The problem is that apparently, after the jQuery function ends the variable bees undefined (even though it was declared outside that scope). The first alert(foo) displays the content of the file properly, but the second one displays nothing.

Can anybody tell me what is happening here?

I have the following code, in which I want to save the content of the file bar.txt in the variable foo:

var foo;

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

alert(foo);

The problem is that apparently, after the jQuery function ends the variable bees undefined (even though it was declared outside that scope). The first alert(foo) displays the content of the file properly, but the second one displays nothing.

Can anybody tell me what is happening here?

Share Improve this question asked Feb 6, 2012 at 10:12 federicotfedericot 12.4k19 gold badges69 silver badges111 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

This is how asynchronous programming works. The $.get function "ends" when the callback handler is called, not in a linear fashion by following the code.

The "first" alert() that will trigger when you run this code is the one you called on the last line (outside $.get the handler), by that time the ajax request has not yet been pleted.

The second alert will happen when the ajax is pleted (inside the $.get handler), and will display the data that you assigned to the variable, ing from the handler argument.

Some ments to your code, hopefully you’ll understand better:

var foo; // foo is now undefined

jQuery.get('http://example./bar.txt', function(data) {
     // the code in this handler will be executed after the ajax is plete
     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

You can program this differently if you need an example on how to "reuse" the foo variable:

var foo;

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

function onData() {
    alert(foo);
}

try

var foo;

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

alert(foo);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744171641a4561564.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信