如何从parseJSON数组中获取每个数据

时间:2017-06-08 09:01:45

标签: php mysql json ajax codeigniter

我正在尝试使用Google图表API绘制线图,我使用PHP codeignitor从mySQL数据库中检索数据。

到目前为止,我能够检索数据,但我无法解析Json数据,并将其填入线图。下面是我实际加载的视图。

<html>
<head>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
  <script type="text/javascript">
    var BASE_URL = "<?php echo base_url(); ?>";
    </script>
 <script type="text/javascript">
  // Load the Visualization API and the line package.
  google.charts.load('current', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(drawChart);

function drawChart() {

     $.ajax({

   type: 'POST',
    url: BASE_URL+'index.php/Chart_varnish/getdata',
    dataType: "json",



    success: function (data1) {
    // Create our data table out of JSON data loaded from server.
    var data = new google.visualization.DataTable();
  data.addColumn('string', 'timeline');
  data.addColumn('string', 'solid');
  var jsonData = $.parseJSON(data1);

  for (var i = 0; i < jsonData.length; i++) {
        data.addRows([jsonData[i].timeline, jsonData[i].solid_t1]);
  }
  var options = {

    title: 'Solid chart',
    width: 900,
    height: 500,

  };

  var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
  chart.draw(data, options);
   }
});
}
  </script>
</head>
<body>

  <div id="line_chart"></div>
</body>
</html>

下面是我的控制器中的函数getdata:

    function getdata(){
  $this->load->model('Chart');
  $this->load->helper('url');
    $data  = $this->Chart->getdata_solid();
    print_r(json_encode($data, true));
}

我尝试输出json_encode数据,我可以得到以下结果:

[{"timeline":"430","solid_t1":"12"},{"timeline":"030","solid_t1":"8.1"},{"timeline":"830","solid_t1":"32"},{"timeline":"1230","solid_t1":"10"},{"timeline":"1630","solid_t1":"100"},{"timeline":"2030","solid_t1":"8"}]

有人可以帮我这个,谢谢。

更新

大家好,我把这个函数放在我的模型中,也许是因为我的查询结果是数组而不是对象?

function getdata_solid(){
  $this->db->select('timeline');
  $this->db->select('solid_t1');
  $this->db->from("varnish_mvs");
  $this->db->where('date_selected', '2017-03-25');
  //$this->db->where('timeline', $timeline);
  $query = $this->db->get();
  return $query->result_array();

}

最终更新:我最终通过更改加载谷歌图表功能的方式解决了这个问题。这是我的最终工作代码。我希望这对有同样问题的人有所帮助。

  

$(document).ready(function() {

     $.ajax({

   type: 'POST',
    //url: 'http://localhost/charts/charts/getdata',
    url: BASE_URL+'index.php/Chart_varnish/getdata',
    dataType: "JSON",
    success: function (data1) {

     // alert(data1);
       // Load the Visualization API and the line package.
  google.charts.load('current', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(function(){
    drawChart(data1);
  });

   }
});

     function drawChart(data1) {

        var data = new google.visualization.DataTable();
  data.addColumn('string', 'timeline');
  data.addColumn('number', 'solid_t1');
  var dataArray = [];
  /*$.each(data1, function(i, obj){
    dataArray.push([obj.timeline, parseInt(obj.solid_t1)]);
  });*/
  var jsonData = $.parseJSON(data1);
   for (var i = 0; i < jsonData.length; i++) {
        dataArray.push([jsonData[i].timeline, parseInt(jsonData[i].solid_t1)]);
      }
  //dataArray.push([jsonData[0].timeline, parseInt(jsonData[0].solid_t1)], [jsonData[1].timeline, parseInt(jsonData[1].solid_t1)])
  //dataArray.push(['2', 3], ['6', 5]);
  alert(dataArray);
  data.addRows(dataArray);
  var options = {
    title:'Solid chart',
    width: 900,
    height: 500,
  };
  var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
  chart.draw(data, options);
     }

});

3 个答案:

答案 0 :(得分:0)

dataType: "json",

确保您期望json作为回复(documentation here),因此您不需要做

var jsonData = $.parseJSON(data1);

data1已经是一个javascript对象

答案 1 :(得分:0)

尝试使用此

    $.post(BASE_URL+'index.php/Chart_varnish/getdata',function(data1){
      $.each(data1,function(index,value){
      data.addColumn(value.timeline,value.solid_t1);
         });
//more CODE HERE
    },'JSON');

我希望它能帮助你解决问题。你也应该像这样回应json

echo json_encode($data1);

答案 2 :(得分:0)

假设PHP脚本的响应是JSON数据,那么您可能会像这样处理响应数据。

function drawChart() {
    $.ajax({
        type: 'POST',
        url: BASE_URL + 'index.php/Chart_varnish/getdata',
        dataType: 'json',
        success: function(response) {
            var dataTbl = new google.visualization.DataTable();
                /* a number for at least 1 column is req'd ? */
                dataTbl.addColumn('string', 'timeline');
                dataTbl.addColumn('string', 'solid');

            /* iterate through the response data */
            for( var n in response ){
                if( response[n] && typeof(response[n])=='object' ){
                    dataTbl.addRows( response[n].timeline, response[n].solid_t1 );
                }
            }
            var options = {
                title: 'Solid chart',
                width: 900,
                height: 500,

            };
            var chart = new google.visualization.LineChart( document.getElementById('line_chart') );
                chart.draw( dataTbl, options );
        }
    });
}

PHP脚本应该只使用json_encode - 第二个参数可以是标志(预定义常量)的按位组合,而不是简单的真/假 - 它是使用/ true的json_decode函数/ false因为它是第二个参数。

function getdata(){
    $this->load->model('Chart');
    $this->load->helper('url');
    $data  = $this->Chart->getdata_solid();

    /* echo rather than print_r */
    echo json_encode( $data );
}