2015-12-03 38 views
0

除了獲取要在圖表中加載的數據以外的所有工作。當我查看頁面源代碼時,它會顯示ajaxData而不是該變量包含的數據數組。將JavaScript變量傳遞給融合圖表構造函數

我試過JSON.Stringify,這個和其他一些方法。我無法在使用AJAX加載數據的融合圖表網站上找到任何示例,它們的所有示例都涉及將JavaScript放在服務器端代碼(如PHP)中,這是我寧願避免的。我只是想用ajax加載數據並將其轉儲到圖表中。

$.ajax($assetsSearchUrl, { 
     dataType: "text", 
     accepts: {text: "application/json"}, 
     success: loadChart 
    }); 

function loadChart(ajaxData) 
{   

    var ageGroupChart = new FusionCharts({ 
     type: 'pie2d', 
     renderAt: 'chartId', 
     width: '400', 
     height: '275', 
     dataFormat: 'json', 
     theme: 'ocean', 
     dataSource: { 
      "chart": { 
       "caption": "Assets", 
       .... 
       "showLegend": "0" 
     }, 
     data : ajaxData 
    } 
}).render(); 
} 

沒有動態數據的工作示例。

FusionCharts.ready(function() { 
var ageGroupChart = new FusionCharts({ 
    type: 'pie2d', 
    renderAt: 'chart-container', 
    width: '450', 
    height: '300', 
    dataFormat: 'json', 
    dataSource: { 
     "chart": { 
      "caption": "Split of Visitors by Age Group", 
      .... 
      "legendItemFontColor": '#666666' 
     }, 
     "data": [ 
      { 
       "label": "Teenage", 
       "value": "1250400" 
      }, 
      { 
       "label": "Senior", 
       "value": "491000" 
      } 
     ] 
    } 
}).render(); 
}); 

回答

2

我想我有你所希望的。我使用JSON.parse將json文件字符串轉換爲對象,不需要PHP。希望這可以幫助!

var jsonUrl = "https://api.myjson.com/bins/1jq6x"; 

FusionCharts.ready(function() { 

    $.ajax(jsonUrl, { 
    dataType: "text", 
    accepts: { 
     text: "application/json" 
    }, 
    success: loadChart 
    }); 

    function loadChart(jsonString) { 
    var ageGroupChart = new FusionCharts({ 
     type: 'pie2d', 
     renderAt: 'chart-container', 
     width: '450', 
     height: '300', 
     dataFormat: 'json', 
     dataSource: { 
     "chart": { 
      "caption": "Split of Visitors by Age Group", 
      "legendItemFontColor": '#666666' 
     }, 
     "data": JSON.parse(jsonString) 
     } 
    }).render(); 
    } 
}); 

JSFiddle

+0

非常感謝!這正是我需要的。我現在可以看到我做錯了什麼。起初我錯誤地認爲它與構造函數有關,但是這清楚地向我說明了它是在後端返回'data'作爲JSON的一部分。你的例子清除了我的錯誤。再次感謝! – blur0224