Using variable outside of ajax callback function

前端 未结 4 824
一生所求
一生所求 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:35

    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.

提交回复
热议问题