2017-08-04 70 views
1

我是新的web開發尤其是jquery等。在我的代碼中,morris圖表被認爲是來自ajax請求的數據。下面的代碼片段
HTML
Morris圖表undefined使用jquery ajax php

<div id = "node" class = "something">//some divs here</div> 
<div id = "myModal role = "dialog">//some divs here again 
<div class = "modal-body"><div id = "my_chart"></div></div></div> 

的Javascript

<script type="text/javascript"> 
$(document).ready(function(){ 
    var chart_data = ''; 
    var div_id = ''; 

    $(".something").click(function(){ 
    div_id = jQuery(this).attr("id"); 
    $.ajax({ 
     type : 'POST', 
     url : 'test1', 
     data : { "node_num" : div_id}, 
     success: function(data){ 
     chart_data = data; 
     console.log(chart_data); 
     $('#myModal').modal(); 
     }, 
     error: function(data){ 
     alert("Something went wrong, please refresh"); 
     } 
    }); 
    }); 


    $("#myModal").on('shown.bs.modal', function(){ 
    $('#my_chart').empty(); 
     var chart = Morris.Area({ 
     element: 'my_chart', 
     data: chart_data, 
     xkey: 'time', 
     ykeys:['power'], 
     labels:['Power(Watts)'], 
     pointSize: 2, 
     hideHover: 'auto', 
     resize: true, 
     lineColors: ['#1abc9c'], 
     fillOpacity: 0.75, 
     parseTime: false 
     }); 
     }); 

    $(".something").hover(function(){ 
    $(this).css('cursor','pointer'); 
    }) 
}); 

</script> 

PHP

public function test1() 
    { 
     $node_num = $this->input->post('node_num'); 
     $chart = ''; 
     $chart_data = ''; 
     $query = $this->Nodes->get_chartdata($node_num); 

     foreach($query->result() as $row) 
     { 
      $time = substr($row->n_date, -8); 
      $power = ($row->voltage)*($row->current); 
      $chart .= "{ power: ".$power.", time: '".$time."' }, "; 
     } 
     $chart_data = '['.$chart.']'; 
     echo $chart_data; 

    } 

PHP OUTPUT

[{功率:21.837696,時間:'10:59:41' },{功率:2.07552,時間:'11:00:23' },{功率: 14.09736,時間:'11:00:42'},{power:10.149408,time:'11:03:52'},{power:20.195136,time:'13:45:01'},]

據推測,morris圖表會顯示圖表like this(我用php輸出替換了數據:chart_data)。相反,我得到this。我遵循其他方法,但它仍然是一樣的。任何幫助我如何解決這個問題?提前感謝你!

回答

0

對於圖表更新,您需要使用setData

chart.setData(chart_data);

注:

1:你需要通過數組對象繪製不串。

第二:在PHP側構建陣列,公正與json_encode();

3呼應:在Ajax調用

+0

現在我明白了補充dataType:'json',。非常感謝!我終於得到了我需要的東西。 –