2

我正在寻找使用 jqplot 插件(http://www.jqplot.com/tests/pie-donut-charts.php)来生成饼图,但是我无法从我的 $get 函数中获取结果jqplot 函数将接受作为可用数据的东西。

您可以在上面的 jqplot 链接中看到我需要如何创建数据变量来显示饼图。

这是我的 $.get 函数,它当前返回一个字符串:

//data is returned as a string: 'some_field_name',10,'some_other_field,33 etc
$.get("notesajax.php", {month:monthFilter, area:areaFilter}, function(data) {
    var arr = data.split(",");
    var results = [];
    for (var i = 0; i < arr.length; i++) {
        mini = [];
        mini[arr[i]] = "'"+arr[i]+"',"+arr[i+1];
        results.push(mini);
        i++;
    }

为了便于参考,这里是 jqplot 函数,包括在开头定义的“数据”变量,以说明 jqplot 期望如何接收数据。

//this variable is just for illustrative purposes
var data = [
    ['Heavy Industry', 12],['Retail', 9], ['Light Industry', 14], 
    ['Out of home', 16],['Commuting', 7], ['Orientation', 9]
];

var plot1 = jQuery.jqplot ('chartdiv', [results], 
    { 
        seriesDefaults: 
        {
            // Make this a pie chart.
            renderer: jQuery.jqplot.PieRenderer, 
            rendererOptions: {
                // Put data labels on the pie slices.
                // By default, labels show the percentage of the slice.
                showDataLabels: true
            }
        }, 
        legend: { show:true, location: 'e' }
    }
);

但是到目前为止,我无法将我的 $get 返回数据转换为 jqplot 函数将接受的格式。

4

3 回答 3

1
var field, value, data = [], str = "'some_field_name',10,'some_other_field,33";
var arr = str.split(',');
// just add 2 to each iteration to get every second item (last argument is i += 2):
for (var i = 0; i < arr.length; i += 2) {
  field = arr[i].replace(/'/g, ""); // replace ', because otherwise your string will be "'some_field_name'"
  value = parseInt(arr[i+1], 10); // parseInt because you want numbers, but got a string
  data.push([field, value]); // push into your data-array an array with your field and value
}

jsfiddle在这里:http: //jsfiddle.net/wLxyZ/

于 2013-06-11T10:16:58.917 回答
0

You are generating wrong array. you should either send directly JSON object back from the server which is recommended and easy or make your parsing script ok.

$.get("notesajax.php", {month:monthFilter, area:areaFilter}, function(data) {
var arr = data.split(",");
var results = [];
for (var i = 0; i < arr.length; i++) {
    var mini = new Array();
    mini.push(arr[i]);
    mini.push(arr[i+1]);
    results.push(mini);
}
于 2013-06-11T10:18:17.233 回答
0

i played with your code and came to the following solution, there was couple of issues with your original code especially on how you constructed your mini array

var arr = ['some_field_name',10,'some_other_field',33];
var results = [];
for (var i = 0; i < arr.length; i+=2) {        
    var mini = ["'"+arr[i]+"'",+arr[i+1]];
    results.push(mini);
}
alert(results[0][0]);
于 2013-06-11T10:21:13.330 回答