Using variable outside of ajax callback function

匿名 (未验证) 提交于 2019-12-03 01:27:01

问题:

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);     }); 

回答1:

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    } }); 


回答2:

console.log(icon); won't have a value at that point as you're doing asynchronous ajax. Move your entire code that handles the response in the callback function or functions it calls.

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


回答3:

The problem is that $.get is queuing a request, but does not execute the request synchronously; it returns immediately. JavaScript is not multi-threaded!

You will have to execute console.log(icon) inside the callback function. At the point that line is being executed, the AJAX call has not completed yet.

The global icon variable will be set from the callback; your code is correct in that regard.



回答4:

It can help to visualize the code like this.

    var icon;      $(function(){         $.get('data.xml', callback); // sends ajax request         // next line happens immediately unless ajax request is set to synchronous         console.log(icon); // logs undefined     });     function callback(xml){ // onsuccess callback happens         icon = xml.documentElement.getElementsByTagName("icon");         console.log(icon); // logs Array     } 

I removed the anonymous function and placed the callback after the console.log. Like others have pointed out the ajax callback happens asynchronously, while javascript continues to execute.



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