javascript - global variable not in scope after being defined in callback?

若如初见. 提交于 2019-12-23 18:05:34

问题


whenever i try to run something like the following, firebug tells me that "markers is undefined" at the line "for (var i=0 ..."

but i declared markers as a global variable at the top right...?

var markers;
function load() {

  $.get("phpsqlajax_genxml.php", function(data) {
    markers = data.documentElement.getElementsByTagName("marker");
  });

  for (var i = 0; i < markers.length; i++) {
    var name = markers[i].getAttribute("name")
    //do more stuff
    }
}

but when i do this, it works.

var markers;
function load() {

  $.get("phpsqlajax_genxml.php", function(data) {
      markers = data.documentElement.getElementsByTagName("marker");
      makeMarkersWithXMLinfo(); 
  });

  function makeMarkersWithXMLinfo() {
      for (var i = 0; i < markers.length; i++) {
             var name = markers[i].getAttribute("name")
             //do more stuff
      }
  }
}

i'm not even passing "markers" as an argument to my makeMarkersWithXMLinfo() function. but yet it works. what's going on? thnx


回答1:


The problem you're having is that get starts an asynchronous operation. So your code immediately following the call to get happens before the success callback on the get is run. E.g. (see the comments):

var markers;
function load() {

  // ===> This happens FIRST
  $.get("phpsqlajax_genxml.php", function(data) {
    // ===> This happens THIRD, some time after `load` returns
    markers = data.documentElement.getElementsByTagName("marker");
  });

  // ===> This happens SECOND
  for (var i = 0; i < markers.length; i++) {
    var name = markers[i].getAttribute("name")
    //do more stuff
    }
}

Your second example is the correct way to code it (although I'd recommend avoiding a global entirely), because you're using markers only after the GET has completed.




回答2:


$.get is asynchronous, that means that if you call something immediatly after $.get, it's callback function wouldn't be invoked yet, and your global would still be undefined.



来源:https://stackoverflow.com/questions/8960803/javascript-global-variable-not-in-scope-after-being-defined-in-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!