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

Javascript global variables only accessible after application runs

本文关键字:运行 访问 应用程序 全局变量 Javascript      更新时间:2023-09-26

我有一系列嵌套的Ajax请求到外部api,这是非常丑陋的,但这是唯一的方法,我可以弄清楚如何以指定的顺序进行调用,每个调用利用从前一个调用带回的一些值。(我尝试过,但不能让它工作,所以我回到这里的建议。)

无论如何,这在一定程度上是有效的。我所有的调用都是连续工作的,最后得到一个名为people的数组,它只是一个名称列表:["name1","name2","name3"]

我的问题是,我似乎不能做任何事情与这个数组从我的javascript代码。我不能将它们附加到div中,也不能在代码执行期间警告它们,甚至不能在console.log 中记录它们。然而,一旦我的代码完成,我可以在浏览器控制台中输入people,它们都在那里,如预期的那样。

我猜这与变量的范围有关-我曾尝试使其全局并移动其声明的位置,但我可以从可运行代码访问people的唯一方法是从最后的AJAX循环内,然后我得到很多重复的值,因为它正在循环并增量地添加到数组中。

这里的目标是获得最终API调用的人员并在HTML中列出他们。

这是我的代码。如有任何建议,不胜感激。

HTML触发事件:

<input type='file' accept='image/*' onchange='openFile(event)'>
<!--process is triggered by file upload-->
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
                                    }); 
                                } 
                            }); 
                        }); 
                    }
                });
            });
        }
    }); 
} 

从您的代码中可以看到,people变量将只在您调用openfile函数时创建。如果你想要它被创建,即使openfile方法没有被调用,然后在所有的函数之外声明它,然后它将是可访问的,或者在你打算在ajax调用上面使用它的地方声明它,然后使用它。

你试过把它放在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;
})();

,然后你可以像

这样调用它
var myOpenFile = new OpenFile();
var people = myOpenFile.people;
myOpenFile.getGraph();
console.log(people);

的额外好处是,OpenFile对象在代码加载后立即可用。代码中的所有变量仅作用于对象OpenFile,并且不污染全局名称空间,您可以通过将它们放在最后的返回语句中来选择希望向其他人公开的内容。