开发者

Javascript - Object loses its value on function exit

I've got this strange problem. In my code, I have a variable named val1 which gets a value after a jQuery call, but after exiting the j开发者_如何学CQuery function it loses its value.

Here's the code:

var val1;
$.getJSON('some address', null, function (result) {
    val1 = result.names[0].name;
    alert(val1); //first alert
});
alert(val1); // second alert

On first alert, I get the needed value, but on the second Alert - I get undefined.

Why?


The second alert is executed before the value is set. Or vice versa: The callback is executed after the second alert.

The Ajax call is asynchronous.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜