-2
function getData() {
    var photo,
        comment,
        url;

    $.getJSON('http://url.info/verify/settings.php', function (data) {
        photo = data.photoMSG;
        comment = data.commentMSG;
        url = data.photoURL
    });
    console.log(photo); //undefined
    console.log(comment); //undefined
    console.log(url); //undefined
}

I'm getting undefined in console log for all of them... How to get these 3 vars visible outside of getJOSN block? I know this have been asked x100 times, I tried windiw.varName but still the same thing..

4

2 回答 2

1

这不是范围问题,而是异步问题。处理程序中的所有内容getJSON都是异步的——因此console.log调用通常会在分配变量之后发生。改用异步回调:

$.getJSON('http://url.info/verify/settings.php', function (data) {
    photo = data.photoMSG;
    comment = data.commentMSG;
    url = data.photoURL;
    callback(photo, comment, url);
});
function(photo, comment, url) {
    console.log(photo); //undefined
    console.log(comment); //undefined
    console.log(url); //undefined
}
于 2013-07-25T21:44:58.947 回答
0

因为$.getJSON正在做一个ajax调用,但是之后的代码是在调用内部回调之前getJSON调用的。所以变量仍然是未定义的。异步行为的典型“问题”。

于 2013-07-25T21:46:05.283 回答