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 badges2 Answers
Reset to default 7This 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条)