C3:读取PHP生成的JSON

时间:2015-11-19 17:33:46

标签: php mysql json c3.js

我是C3(和.js)的新手,但对它能做的事情印象非常深刻和兴奋。

我使用PHP根据以下教程从MySQL中提取数据集: http://www.d3noob.org/2013/02/using-mysql-database-as-source-of-data.html

我可以使用以下代码在PHP中成功生成JSON文件:

 @Override
    public void recyclerViewOnClickListener() {
        recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(this,
                        new RecyclerItemClickListener.OnItemClickListener() {
                            @Override
                            public void onItemClick(View view, int position) {

                                if (restaurants.get(position).isOpen()) {
                                    Intent i = new Intent(HomeActivity.this, MenuActivity.class);

                                    i.putExtra("restaurant", restaurants.get(position));
                                    i.putExtra("userAddress", address);

                                    startActivity(i);

                                }

                            }
                        })
        );
    }

这会生成以下JSON:

$myquery = "SELECT  `date`, `close` FROM  `data2`";
$query = mysql_query($myquery);

if ( ! $query ) {
   echo mysql_error();
    die;
}

$data = array();

for ($x = 0; $x < mysql_num_rows($query); $x++) {
   $data[] = mysql_fetch_assoc($query);
}

$output=json_encode($data); 
echo $output;
?>

我的问题是我拥有的c3.js代码不会呈现图表。不确定这是否是因为JSON格式正确。

这是我使用

的代码
[{"date":"1-May-12","close":"58.13"},{"date":"30-Apr-12","close":"53.98"},{"date":"27-Apr-12","close":"67.00"},{"date":"26-Apr-12","close":"89.70"},{"date":"25-Apr-12","close":"99.00"},{"date":"24-Apr-12","close":"130.28"},{"date":"23-Apr-12","close":"166.70"},{"date":"20-Apr-12","close":"234.98"},{"date":"19-Apr-12","close":"345.44"},{"date":"18-Apr-12","close":"443.34"},{"date":"17-Apr-12","close":"543.70"},{"date":"16-Apr-12","close":"580.13"},{"date":"13-Apr-12","close":"605.23"},{"date":"12-Apr-12","close":"622.77"},{"date":"11-Apr-12","close":"626.20"},{"date":"10-Apr-12","close":"628.44"},{"date":"9-Apr-12","close":"636.23"},{"date":"5-Apr-12","close":"633.68"},{"date":"4-Apr-12","close":"624.31"},{"date":"3-Apr-12","close":"629.32"},{"date":"2-Apr-12","close":"618.63"},{"date":"30-Mar-12","close":"599.55"},{"date":"29-Mar-12","close":"609.86"},{"date":"28-Mar-12","close":"617.62"},{"date":"27-Mar-12","close":"614.48"},{"date":"26-Mar-12","close":"606.98"}]

这是我在图表中得到的结果: c3空白图表 - http://imgur.com/SHPmVOb

任何帮助都会感激不尽,因为我觉得这可能是学习C3的重要障碍。

由于

1 个答案:

答案 0 :(得分:0)

问题可能是json_encode将JSON作为字符串返回。所以它并不是你收到的真正的JSON。使用JSON.parse(来自json_encode的数据);获取JS JSON对象并从那里开始。