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

时间:2015-05-16 04:57:52

标签: javascript jquery arrays ajax

我有一系列对外部API的嵌套Ajax请求,这非常难看,但这是我能够找到如何以指定的顺序进行调用的唯一方法,每次调用都使用从前一次调用带回的一些值。 (我尝试this但无法让它工作,所以我恢复了建议here。)

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

我的问题是我似乎无法使用我的javascript代码对此数组执行任何操作。我不能将它们附加到div,也不能提醒它们,甚至在代码执行期间控制它们 。但是,一旦我的代码完成,我就可以在浏览器控制台中键入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
                                    }); 
                                } 
                            }); 
                        }); 
                    }
                });
            });
        }
    }); 
} 

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您是否尝试将其放入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,并且不会污染全局命名空间,您可以通过将它们放在最后的return语句中来选择您希望向其他人公开的内容。