gpt4 book ai didi

javascript - 将 $get 结果字符串转换为 javascript 数组

转载 作者:行者123 更新时间:2023-11-30 05:47:39 26 4
gpt4 key购买 nike

我正在寻找使用 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 函数可接受的格式。

最佳答案

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/

关于javascript - 将 $get 结果字符串转换为 javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17041496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com