开发者

Javascript - Object loses its value on function exit

开发者 https://www.devze.com 2023-02-11 02:50 出处:网络
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.

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

精彩评论

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