Morris.js setData不起作用,除非我这样做

时间:2019-04-05 20:53:27

标签: json ajax morris.js

我正在根据数据库结果绘制数据图形并通过ajax获取数据。该图应该基于使用jquery setData的查询重绘。我问过其他在工作的程序员,但仍然想不通。

php代码

if(isset($_POST['data'])){

        $data = $_POST['data'];
        $data = json_decode($data);


        $query = "SELECT * FROM bad_errors WHERE rel = '$data' LIMIT 20";

        $result = $db->query($query);
        $chart_data = '';
        while($row = mysqli_fetch_array($result))
        {

          $month = date("M", strtotime($row['date_time']));

          $chart_data .= "{ month:'".$month."', website:".$row["rel"].", code:".$row["code"]."}, ";
        }
        $chart_data = substr($chart_data, 0, -2);


      $data = json_encode($chart_data);
       echo $data;

}

jquery代码

let barChart = Morris.Bar({
   element : 'chart',
   data:[],
   xkey:'month',
   ykeys:['website', 'code'],
   labels:['website', 'code'],
   hideHover:'auto',
   stacked:true
  });



let json = JSON.stringify(rel);
  $.ajax({
        url: "ajax-php/morris-data.php",
        type: "POST",
        data: {data: json},
        dataType:"json",
        success: function (data) {

        //data variable only redraws the graph if data looks like this -  

data = [
{ month:'Mar', website:38, code:547}, { 
month:'Mar', website:38, code:584}, { month:'Mar', website:38, 
 code:500}, { month:'Mar', website:38, code:564}, { month:'Mar', 
 website:38, code:500},
  ]
        barChart.setData(data); // but not here via ajax success
  },


 });

1 个答案:

答案 0 :(得分:1)

我在php中处理数据错误

    while($row = mysqli_fetch_array($result))
    {
     $month = date("M", strtotime($row['date_time']));

      $data[] = array(
        'month' => $month,
        'website' => $row['rel'],
        'code' => $row['code']
      );

    }

$data = json_encode($data);
echo $data;