我在使用 jQuery flot 时遇到问题。
PHP 输出(不是 JSON):
[[1, 153], [2, 513], [3, 644]] ~~ [[1, 1553], [2, 1903], [3, 2680]]
jQuery 调用:
$.ajax({
url: 'xxx.php',
success: function (data) {
var dataArray = data.split('~~'),
dataArray1 = dataArray[0],
dataArray2 = dataArray[1],
plot = $.plot($('#xxx'), [{
data: dataArray1,
color: colours[0]
},
{
data: dataArray2,
color: colours[1],
points: {
show: true,
}
},
], {
series: {
bars: {
show: true,
barWidth: .6,
align: 'center'
}
},
grid: {
show: true,
hoverable: true,
clickable: true,
autoHighlight: true,
borderWidth: true,
borderColor: 'rgba(255, 255, 255, 0)'
},
xaxis: {
show: false
}
});
}
});
以这种方式获取数据,我尝试使用 jQuery Flot 但不起作用...
然而,我可以通过分离数据:
第一个标签:
[[1, 153], [2, 513], [3, 644]]
第二个标签:
[[1, 1553], [2, 1903], [3, 2680]]
最佳答案
为了基本理解,我将分享一个带有 ajax 的简单示例 jquery Flot。
看到这个页面并将其更改为ajax:http://www.jqueryflottutorial.com/making-first-jquery-flot-line-chart.html
首先,您必须在不使用 ajax 的情况下成功显示所描述的图表。如果您不包含 css 文件,请不要忘记将高度和宽度放入 div 标签中。:
<div id="flot-placeholder" style="width: 100%; height: 260px"></div>
如果没问题,请按照此步骤操作。
第 1 步:将脚本放入函数中:
<script>
function show_chart(data) {
// this will be moved to php file
//var data = [[1, 130], [2, 40], [3, 80], [4, 160], [5, 159], [6, 370], [7, 330], [8, 350], [9, 370], [10, 400], [11, 330], [12, 350]];
var dataset = [{label: "line1",data: data}];
var options = {
series: {
lines: { show: true },
points: {
radius: 3,
show: true
}
}
};
$(document).ready(function () {
$.plot($("#flot-placeholder"), dataset, options);
});
}
</script>
第2步:创建sample.php。
<?php
require 'config.php';
if($_POST)
{
$id = $_POST['id'];
$arr = array();
$arr = [[1, 130], [2, 40], [3, 80], [4, 160], [5, 159], [6, 370], [7, 330], [8, 350], [9, 370], [10, 400], [11, 330], [12, 350]];
echo json_encode($arr);
}?>
注意:从第一个脚本移动的 $arr 然后仅成为示例数据。您应该创建一个 php 类或函数,从数据库获取数据并以数组格式返回,如 $arr 所示。
第 3 步:创建简单的 ajax 来获取响应并渲染图表:
var id = 1;
$.post('/..if any folder../sample.php', {
id : id,
}, function(response){
var data = JSON.parse(response);
show_chart(data); // call function and render the chart in <div id="flot-placeholder"></div>
});
步骤完成。
在某些情况下,我们可能需要两种或多种数据类型。然后只需将其添加到代码中:
sample.php 内部:
$arr1 = array();
$arr2 = array();
$arr1 = [[1, 130], [2, 40], [3, 80], [4, 160], [5, 159], [6, 370], [7, 330], [8, 350], [9, 370], [10, 400], [11, 330], [12, 350]];
$arr2 = [[1, 130], [2, 40], [3, 80], [4, 160], [5, 159], [6, 370], [7, 330], [8, 350], [9, 370], [10, 400], [11, 330], [12, 350]];
// put more if rquired
echo json_encode($arr1,$arr2); // put more array if required
ajax 内部:
var data = JSON.parse(response);
var result1 = data[0]; // response data from $arr1
var result2 = data[1]; // response data from $arr2
抱歉,描述太长。希望它会有所帮助。
只是为了好玩:
有些人不想在控制台日志中显示“sample.php”。为此,我们可以简单地将“sample”更改为文件夹并在其中创建index.php,然后在ajax中将url定向到该文件夹,如下所示:
$.post('/..if any folder../sample/'), { // this will open index.php
关于javascript - 使用 jQuery Flot 通过 AJAX 接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16277958/