javascript - 使用jquery ajax函数接收PHP数据并将其附加到anychart中
问题描述
我正在使用 AnyChart 从我的数据库中发布数据。我正在尝试使用 ajax 函数获取最后一个条目并在图表上更新它,以便图表流式传输实时数据。当我调用 ajax 函数时,如何使用带有 setInterval 的 ajax 函数将 PHP 数据附加到图表中?
我的 get-data.php 文件 -
$sql = "SELECT * FROM (SELECT * FROM table ORDER BY id DESC LIMIT 1) AS `table` WHERE table.id mod 1 = 0 ORDER by id ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$open_time = $row['open_time'];
$open_time * 10000;
$open_time = date("m/d/Y h:i a", $open_time);
$low = $row['low'];
$open = $row['open'];
$close = $row['close'];
$high = $row['high'];
$volume = $row['volume'];
echo "{'x':'".$open_time."','open': ".$open.",'high': ".$high.",'low': ".$low.",'close': ".$close.",'volume': ".$volume."},";
}
}
我的 main.php 文件 -
anychart.onDocumentReady(function() {
var table = anychart.data.table('x');
// $chart_data is a variable to pull all data from database to set the initial chart
table.addData([<?php echo $chart_data;?>]);
// Ajax request to append last row from database
setInterval(function(){
$.ajax({
type:"post",
url:"get-data.php",
success:function(data){
// This will work
table.addData([ {'x':'08/09/2020 10:11','open': 11000,'high': 10000,'low': 8000,'close': 8500, 'volume':344}]);
// This returns NULL
table.addData([ data ]);
}
});
}, 2000);
var chart = anychart.stock(true);
var mapping = table.mapAs({
'date': 'date',
'open': 'open',
'high': 'high',
'low': 'low',
'close': 'close',
'volume': 'volume',
'fill': 'fill'
});
var plot = chart.plot(0);
chart.container('container');
var series = chart.plot(0).candlestick(mapping);
chart.scroller().xAxis(false);
chart.scroller().enabled(false);
chart.draw();
});
当我使用此方法时,我收到错误“无法读取 null 的属性 'x'”,因此它显然没有正确返回数据。如果我用文字字符串数据替换 ajax 请求函数中的“数据”变量,它工作正常,所以它一定是我回显数据的方式的问题。如何使用 setInterval 将数据从 get-data.php 正确传递到 ajax 函数以实时更新价格?
解决方案
我发现我需要在 php 文件中创建一个 JSON 数组 -
$data_array = array(
'open_time' => $open_time,
'open' => $open,
'high' => $high,
'low' => $low,
'close' => $close,
'volume' => $volume,
);
echo json_encode($data_array);
然后在 ajax 函数中准备这些数据 -
setInterval(function(addData){
$.ajax({
type:"POST",
dataType : 'json',
url:"stream-last.php",
success:function(data){
var open_time = data['open_time'];
var open = data['open'];
var high = data['high'];
var low = data['low'];
var close = data['close'];
var volume = data['volume'];
//table.remove(0);
table.addData([ {'x':open_time,'open':open,'high':high,'low':low,'close':close, 'volume':volume } ]);
}
});
}, 2000);
推荐阅读
- typescript - 如果结合 saga 测试 (*.spec.ts) 和组件测试 (*tsx),使用 mocha 运行测试会超时
- c# - 在远程数据库上运行 find 方法时,具有 AutoMapper 的实体框架 6 通用存储库会降低性能
- bash - 在 Bash 中,如何编写一个返回字符串来设置 var 的函数,并将日志也输出到 stdout?
- javascript - 参数类型的 WebStorm NoInspection 不可分配
- git - 如何在 SWIFT 中反转到上一个分支?
- java - Hibernate Search 和 Lucene 给出 FileNotFoundException
- asp.net - 如何在 asp.net 5 windows 身份验证中设置重定向 URL
- wordpress - 优化大型 WP 查询
- angular - 如何在 ssr 中调用 http api 请求
- azure - 如何增加 Azure AD B2C 上的守护程序应用程序的令牌生命周期