首页 > 解决方案 > 使用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 函数以实时更新价格?

标签: javascriptphpjqueryajaxanychart

解决方案


我发现我需要在 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);

推荐阅读