Using variable outside of ajax callback function

前端 未结 4 816
一生所求
一生所求 2020-12-10 22:50

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

    var icon; 
    $(function(){

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

                 


        
4条回答
  •  遥遥无期
    2020-12-10 23:30

    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.

提交回复
热议问题