使用json_encode编码PHP数据并在js文件中使用它的问题

时间:2015-02-05 14:46:26

标签: javascript php arrays json chart.js

好的,我在StackOverflow上阅读了很多问题,但似乎无法解决我的问题。

我有一个php这样的文件:

        <?php
            require "config.php";
            try {
                $conn = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
            }
            catch(PDOException $e) {
                die("Database connection could not be established.");
            }
            $conn->exec("SET NAMES UTF8");
            $sql = "SELECT result.year, SUM(result.grade) AS year_total_points
                    FROM (
                        SELECT *
                            FROM students AS s
                            INNER JOIN points AS p
                            ON s.fn = p.student_fn
                    ) result
                    GROUP BY result.year
                    ORDER BY year_total_points DESC";
            $query = $conn->query($sql);
            if($query->rowCount() > 0) {
                $data = array (
                    "years" => [],
                    "years_total_points" => [],
                    );
                while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
                    $data['years'][] = $row['year'];
                    $data['years_total_points'][] = $row['year_total_points'];
                }
                echo json_encode($data);
            }
            else {
                echo mysql_error();
            }

            $conn = null;
        ?>

长话短说明我对数据库进行查询,得到一个包含year列和year_total_points列的表格。我想将数据存储在关联数组中,以便将其传递给js文件。因为我稍后在js文件中需要一个包含所有年份的数组作为字符串,并且所有点的数组也需要作为字符串,所以我决定将它们存储在关联数组中。但是我认为json_encode没有按原样对其进行编码,因为执行以下代码:

        function success(data){
            var barChartData = {
                labels : data["years"],
                datasets : [
                    {
                        fillColor : "rgba(151,187,205,0.5)",
                        strokeColor : "rgba(151,187,205,0.8)",
                        highlightFill : "rgba(151,187,205,0.75)",
                        highlightStroke : "rgba(151,187,205,1)",
                        data : data["years_total_points"]
                    }
                ]
            }
            var ctx = document.getElementById("myChart").getContext("2d");
            window.myBar = new Chart(ctx).Bar(barChartData, {
                responsive : true
            });
        }

        function error(){
            alert('Error!');
        }

        window.onload = function(){
            $.ajax({url: "http://localhost/year_comparison.php"}).done(success).error(error);
        }

它说数据[&#34;年&#34;]未定义,我希望它类似于["2011", "2012", "2013"]。查询的所有内容都可以,因为当我添加alert(data);时,我得到了结果{"years":["2011"],"years_total_points":["85.98"]}。但是alert(data["years"])undefined。任何帮助解决这个问题将不胜感激。

0 个答案:

没有答案