最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

No access to global variable from inside a function? (javascript) - Stack Overflow

programmeradmin6浏览0评论

This is not the first time I am working with ajax and such, I want to use the jQuery function $.getJSON

I have written the following:

var newIMG;

function random_img(){
    $.getJSON('content/random.php',function (data){
        newIMG = data;
    })      
    alert(newIMG.ERROR);
}

But for some reason I can't access the newIMG variable after the JSON request has been made. Passing it from the $.getJSON function to the random_img() function in some way would be fine as well (better, actually)

It's really strange and I can't figure out what's the problem here.

.jpg Screenshot of the firebug console, may explain it better.

Thanks in advance guys.

This is not the first time I am working with ajax and such, I want to use the jQuery function $.getJSON

I have written the following:

var newIMG;

function random_img(){
    $.getJSON('content/random.php',function (data){
        newIMG = data;
    })      
    alert(newIMG.ERROR);
}

But for some reason I can't access the newIMG variable after the JSON request has been made. Passing it from the $.getJSON function to the random_img() function in some way would be fine as well (better, actually)

It's really strange and I can't figure out what's the problem here.

https://i.sstatic/OShao.jpg Screenshot of the firebug console, may explain it better.

Thanks in advance guys.

Share Improve this question asked Apr 9, 2011 at 17:46 CookieMonsterCookieMonster 1,2374 gold badges15 silver badges30 bronze badges 1
  • You are also missing a ; after the }) – Hogan Commented Apr 9, 2011 at 17:51
Add a ment  | 

2 Answers 2

Reset to default 6

It's because you're trying to alert before the JSON request has e back (getJSON is asynchronous) so when it first attempts to alert it, it is undefined.

Move the alert into the callback as such:

$.getJSON('content/random.php',function (data){
  newIMG = data;
  alert(newIMG.ERROR);
});     

Your call to $.getJSON is asynchronous, which means that alert(newIMG.ERROR) will be evaluated before the Ajax call has returned a value. You need to place the alert call inside the callback:

var newIMG;

function random_img(){
  $.getJSON('content/random.php',function (data){
    newIMG = data;
    alert(newIMG.ERROR);
  });      
}
发布评论

评论列表(0)

  1. 暂无评论