2016-01-02 43 views
1

我想从jquery ajax调用中加载一些数据到nvD3图表。如果我不包括Ajax调用图表工作完全正常,但根本不会,如果我尝试Ajax调用后作出加载数据加载..Javascript nvD3图表不等待AJAX​​调用完成

<script> 
    angular.module('app', ['onsen']) 

     nv.addGraph(function() { 
      var chart = nv.models.discreteBarChart() 
       .x(function(d) { return d.label }) //Specify the data accessors. 
       .y(function(d) { return d.value }) 
       .staggerLabels(true) //Too many bars and not enough room? Try staggering labels. 
       .tooltips(false)  //Don't show tooltips 
       .showValues(true)  //...instead, show the bar value right on top of each bar. 

       ; 

      d3.select('#chart svg') 
       .datum(exampleData()) 
       .call(chart); 

      nv.utils.windowResize(chart.update); 

      return chart; 
     }); 

     //Each bar represents a single discrete quantity. 
     function exampleData() { 
      $.ajax({ 
       type: "GET", 
       url: "https://demo8162910.mockable.io/json", 
       dataType: 'jsonp', 
       jsonp: true, 
       jsonpCallback: "myJsonMethod", 
       error: function(){ 
        console.log('Unable to load feed, Incorrect path or invalid feed'); 
       }, 
       success: function(data){ 
        console.log('feed done'); 
        return [ 
           { 
            key: "Cumulative Return", 
            values: [ 
            { 
             "label" : "A Label" , 
             "value" : -29.765957771107 
            } , 
            { 
             "label" : "B Label" , 
             "value" : 0 
            } , 
            { 
             "label" : "C Label" , 
             "value" : 32.807804682612 
            } , 
            { 
             "label" : "D Label" , 
             "value" : 196.45946739256 
            } , 
            { 
             "label" : "E Label" , 
             "value" : 0.19434030906893 
            } , 
            { 
             "label" : "F Label" , 
             "value" : -98.079782601442 
            } , 
            { 
             "label" : "G Label" , 
             "value" : -13.925743130903 
            } , 
            { 
             "label" : "H Label" , 
             "value" : -5.1387322875705 
            } 
            ] 
           } 
           ]     

       }}); 

     } 

    </script> 

回答

1

我认为你需要把

d3.select('#chart svg') 
      .datum(exampleData()) 
      .call(chart); 

在你的success函数内,用数据本身替换exampleData()