简体   繁体   English

仅在应用程序运行后才能访问Javascript全局变量

[英]Javascript global variables only accessible after application runs

I have a series of nested Ajax requests to external APIs, which is very ugly but it was the only way I could figure out how to make calls in a specified order with each call utilizing some values brought back from the previous call. 我对外部API有一系列嵌套的Ajax请求,这很丑陋,但这是我能弄清楚如何以指定顺序进行调用的唯一方法,每个调用都利用从前一个调用返回的一些值。 (I attempted this but couldn't get it to work, so I reverted to the advice here .) (我尝试过此操作,但无法使其正常工作,因此我在此处恢复了建议。)

Anyway, this works well to a point. 无论如何,这很好地达到了目的。 All my calls work in succession, and I end up with an array called people , which is just a list of names: ["name1","name2","name3"] . 我所有的调用都连续工作,最后得到一个名为people的数组,它只是名称列表: ["name1","name2","name3"]

My problem is that I don't seem to be able to do anything with this array from my javascript code. 我的问题是我的JavaScript代码似乎无法使用此数组执行任何操作。 I can't append them to a div, nor can I alert them, or even console.log them during code execution . 我不能将它们附加到div上,也不能提醒它们,甚至不能在代码执行过程中用console.log记录它们。 However, once my code completes, I can type people into the browser console and there they all are, as expected. 但是,一旦我的代码完成,我就可以像预期的那样在浏览器控制台中键入people了。

I am guessing this has something to do with the scope of the variable - I have tried making it global and moving the placement of its declaration, but the only way I can access people from the runnable code is from within the final AJAX loop, and then I get lots of repeating values because it's looping and adding to the array incrementally. 我猜想这与变量的范围有关-我试图使它成为全局变量并移动其声明的位置,但是我可以从可运行代码访问people的唯一方法是在最终的AJAX循环中,并且然后我得到很多重复的值,因为它是循环循环并逐渐添加到数组中。

The goal here is to get people from that final API call and list them in HTML. 这里的目标是从最终的API调用中吸引人们,并以HTML列出他们。

Here's my code. 这是我的代码。 Any suggestions greatly appreciated. 任何建议,不胜感激。

HTML to trigger event: HTML触发事件:

<input type='file' accept='image/*' onchange='openFile(event)'>
<!--process is triggered by file upload-->

javascript: JavaScript的:

    var openFile = function(event) {

    //... Some UI stuff happens here.
    //... When finished, just call getGraph(); below

    performances = new Array();  // global scope
    people = new Array();  // global scope
    getGraph();  // call function below

    console.log(people);   // retrieve array; doesn't work
  };  

   function getGraph(){ 
    $.ajax({
       url:'http://...' + document.getElementById('prDate').value,
       dataType:'json',
       success: function(response){
           $.each(response, function(i, item) {
               var programID = item.id;
                 $.ajax({
                    url:'http://...'+ programID',
                    dataType:'json',
                    success: function(response){
                        $.each(response, function(i, item) {
                            performances.push( item.id );
                        });
                        $.each(performances, function(index, value){
                            $.ajax({
                               url:'http://...' + this.valueOf() +'/persons/',
                               dataType:'json',
                               success: function(response){
                                   $.each(response, function(i, item) {
                                       people.push( item.firstname + ' ' + item.lastname );  // the magic moment
                                    }); 
                                } 
                            }); 
                        }); 
                    }
                });
            });
        }
    }); 
} 

From your code it is visible that people variable will be create only once you call openfile function. 从代码中可以看到,只有在调用openfile函数后,才会创建people变量。 If you want it be created even when the openfile method is not called then declare it outside of all the functions and then it will be accessible or else declare it in the place where you intend to use it like above the ajax call, then use it. 如果即使在未调用openfile方法的情况下openfile创建它,则可以在所有函数之外声明它,然后可以访问它,或者像在ajax调用上方一样在打算使用它的地方声明它,然后使用它。

Have you tried putting it inside a IIFE closure ? 您是否尝试过将其放入IIFE封口中?

(function(){

  var OpenFile = function() {

    if ( !(this instanceof OpenFile) ) {
      return new OpenFile();
    }

    var performances = new Array();   // closure Scope
    var people = new Array();         // closure Scope

    function getGraph(){ 
      $.ajax({
         url:'http://...' + document.getElementById('prDate').value,
         dataType:'json',
         success: function(response){
             $.each(response, function(i, item) {
                 var programID = item.id;
                   $.ajax({
                      url:'http://...'+ programID',
                      dataType:'json',
                      success: function(response){
                          $.each(response, function(i, item) {
                              performances.push( item.id );
                          });
                          $.each(performances, function(index, value){
                              $.ajax({
                                 url:'http://...' + this.valueOf() +'/persons/',
                                 dataType:'json',
                                 success: function(response){
                                     $.each(response, function(i, item) {
                                         people.push( item.firstname + ' ' + item.lastname );  // the magic moment
                                      }); 
                                  } 
                              }); 
                          }); 
                      }
                  });
              });
          }
      }); 
    }

    return {
      get performances() : { return performances;},
      get people()       : { return people; },
      getGraph           : getGraph
    };
  };

  window.OpenFile = OpenFile;

})();

which you can then call by doing something like 然后您可以通过执行类似操作来致电

var myOpenFile = new OpenFile();

var people = myOpenFile.people;

myOpenFile.getGraph();

console.log(people);

with the added benefit that the OpenFile object is immediately available after the code loads. 附加的好处是,代码加载后,OpenFile对象立即可用。 All the variables inside the code are only scoped to the object OpenFile and don't pollute the global namespace and you can choose what you wish to expose to others by putting them in the return statement at the end. 代码中的所有变量仅作用于对象OpenFile,并且不会污染全局名称空间,您可以通过将它们放在最后的return语句中,选择想要公开给他人的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM