Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

javascript - Using variable outside of ajax callback function

What is the best to use global variables outside of a callback function?

    var icon; 
    $(function(){

      $.get('data.xml', function(xml){

           icon = xml.documentElement.getElementsByTagName("icon");
           //this outputs a value
           console.log(icon);
       });
       //this is null
       //How can this maintain the value set above?
       console.log(icon);
    });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The code you have provided is perfectly valid -- and, in fact, icon does "maintain" it's value. The problem, likely, is that get() runs asynchronously -- only calling the anonymous function after 'data.xml' has been fully loaded from the server. So the real-world sequence of execution looks something like this:

  1. call get('data.xml', function(xml){...}) (starts loading data.xml)
  2. call console.log(icon) (icon is still null at this point)
  3. (data.xml finished loading) now the anonymous function is called, which assigns the value to icon: icon = xml.documentElement.getElementsByTagName("icon").

If you want to do something with the value of icon, after the 'data.xml' has been fetched, then you'll need to do it inside the anonymous callback function. Like this:

var icon; 
$(function(){

  $.get('data.xml', function(xml){
       icon = xml.documentElement.getElementsByTagName("icon");
       console.log(icon);
   });
});

good luck!


Note: you can still use icon from code that is outside the anonymous function, but you'll need to wait to access it, until after the anonymous function has been run. The best way to do this is to put the dependent code into its own function, and then call that function from within the callback function:

var icon; 
$(function(){

  $.get('data.xml', function(xml){
       icon = xml.documentElement.getElementsByTagName("icon");
       loadIcon();
   });

   function loadIcon() {
       console.log(icon);
       // ... do whatever you need to do with icon here
   }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...