gpt4 book ai didi

javascript - 如何读取从 ajax 返回的数据数组以获取 google 图表?

转载 作者:行者123 更新时间:2023-11-29 15:25:57 24 4
gpt4 key购买 nike

var e = $.ajax({
type: "POST",
url: "<?php echo $template->get_template_dir('ajax',DIR_WS_TEMPLATES, $current_page_base,'ajax'); ?>/survey_save.php",
data: str
}).done(function(data) {
alert("Survey has been saved."+data);
$('#form').hide();

$('#results').show();
// data array for google chart
var e = [["Element", "Density", { role: "style" } ],["Copper", 8.94, "#b87333"],["Silver", 10.49, "silver"],["Gold", 19.30, "gold"],["Platinum", 21.45, "color: #e5e4e2"]];
return e;
});

google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {

var data = google.visualization.arrayToDataTable(e);

var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);

var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
}

所以上面的代码将数据数组作为 JSON 返回。我需要将其作为数组返回或将 JSON 转换为数组格式。我怎么能那样做?当试图调用

最佳答案

说明:

传递 AJAX 请求并使用 mysql 查询获取 JSON 格式的响应数据。将响应数据馈送到图表函数。

简而言之,无论您是否需要 mysql,您都需要获取数组值 -> 转换为 JSON 并将这些值提供给 google chart。根据您的要求修改代码。

客户端主php

<script>
drawLineChart('<?php echo strtolower($chartType); ?>');
</script>

客户端函数php

function drawLineChart(chartType, chartTitle) {
google.charts.setOnLoadCallback(lineChartData);

function lineChartData() {
var lineChartJsonData = $.ajax({
type: 'GET',
url: "<?php echo $server_script_path; ?>",
data: { id1: chartType, id2: "Chart" },
dataType:"json",
async: false,
beforeSend: function() {
},
success: function(data) {
},
}).responseText;

var options;
options = {
title: chartTitle,
width: '390',
height: '300',
vAxis: {title: '<title>'},
};

var data = new google.visualization.arrayToDataTable(($.parseJSON(lineChartJsonData)));
var chart = new google.visualization.LineChart(document.getElementById(chartType));
chart.draw(data, options);
}
}

服务器端 php 文件

if ($_GET['id1'] != "" && $_GET['id2'] == "Chart") {

// Chart type
$chartType = explode('-', $_GET['id1'])[1];

$sql = "<mysql query>";
$result = mysqli_query($conn, $sql);
$table = array();
$rows = array();
$rows[] = array('<column1>', '<column2>');
while($row = mysqli_fetch_array($result)) {
$rows[] = array('<rows>', '<rows>');
}
$table = $rows;
echo json_encode($table);
}

实时图表(我的数组数据)

enter image description here

关于javascript - 如何读取从 ajax 返回的数据数组以获取 google 图表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39091368/

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