将json链接到javascript以形成图形

时间:2017-05-10 19:25:39

标签: javascript php mysqli

我想根据数据库中的数据显示图表。我使用PHP和Javascript来检索所有数据,然后形成图形。这是我用jason格式转换数据的代码。

$totalrow = mysqli_num_rows($result_set);
$json='[{';
$i = 0;
while($row = mysqli_fetch_assoc($result_set)) {
$i++;
if($i==1) {
    $json.= '"name": "datetime", "data": ["'.$row['datetime'].'"';
}

else if($i==$totalrow) {
    $json.= ']}';
}

else {
    $json.= ',"'.$row['datetime'].'"';
}
}

$json.=', {';
$i = 0;
$result_set2 =  mysqli_query($conn, $SQLSELECT);
while($row = mysqli_fetch_assoc($result_set2)) {
$i++;
if($i==1) {
    $json.= '"name": "PV_Value", "data": ['.$row['PV_Value'];
}

else if($i==$totalrow) {
    $json.= ']}';
}

else {
    $json.= ','.$row['PV_Value'];
}
 }
 $json.= ']';
?>

这是我的javascript,用于根据我在数据库中的数据显示折线图:

$(function () {
$.getJSON('$json', function (data) {

    $('#container').highcharts({
        chart: {
            zoomType: 'x'
        },
        title: {
            text: 'Temperature of PV Value for Process Control'
        },
         subtitle: {
            text: document.ontouchstart === undefined ?
                    'Click and drag in the plot area to zoom in' : 'Pinch  
        the chart to zoom in'
        },

        xAxis: {
            type: 'datetime',
            events: {
                afterSetExtremes: function(e) {
                    alert("Min: "+e.min+"\n"
                            +"Max: "+e.max);
                }
            }
        },
        yAxis: {
            title: {
                text: 'PV Value'
            }
        },
        legend: {
            enabled: false
        },
        plotOptions: {
            area: {
                fillColor: {
                    linearGradient: {
                        x1: 0,
                        y1: 0,
                        x2: 0,
                        y2: 1
                    },
                    stops: [
                        [0, Highcharts.getOptions().colors[0]],
                        [1, 

     Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
                    ]
                },
                marker: {
                    radius: 2
                },
                lineWidth: 1,
                states: {
                    hover: {
                        lineWidth: 1
                    }
                },
                threshold: null
            }
        },

        series: [{
            type: 'area',
            name: 'USD to EUR',
            data: data
           }]
        });
    });
});

问题是我在javascript上的第一个行号($)未定义。

$(function () {

请帮助我解决错误

1 个答案:

答案 0 :(得分:0)

乍一看,我在您的代码中看到以下缺点:

  1. 未定义的$错误可能是因为您还没有包含jquery lib。
  2. 另外,我猜这个$.getJSON('$json'应该是$.getJSON('<?php echo $json?>'
  3. 第三,你在php中创建json的方式并不完全有效。您应该使用json_encode
  4. document.ontouchstart === undefined应为此document.ontouchstart === 'undefined'