dsfliu1129 2014-05-28 14:09
浏览 103
已采纳

返回正确格式化的json响应,以便在Laravel的highcharts中使用

I have a highcharts chart in one of my views and I want the source data to be ajax loaded from a route that returns a json response.

So I made an api route:

Route::get('api/v1/data/{id}', function($id) {
    //Do some stuff and make a key value array with unix timestamp as key and float as value
    $data = Model::getData($id);    
    return $data;
});

I have set up the highchart in my view as in the demo but with my api route as the json source. My chart renders OK but the data is not drawn. There are no errors in the console.

When I view the output of my api route the json output is as follows:

{
    "1317423600": 0,
    "1325289600": -0.17099521359192,
    "1333148400": 0.85133638321359,
    "1341010800": -0.94235521748172,
    "1348959600": 0.37334056741349,
    "1356912000": -0.15089107586321,
    "1364688000": 10.261663055542,
    "1372546800": 9.4860565407533,
    "1380495600": 6.2120398914028,
    "1388448000": 8.7469537358921,
    "1396220400": 8.7985530414845,
    "1398812400": 7.633928980909
}

While the demo json output is like this:

[
  [1147651200000,67.79],
  [1147737600000,64.98],
  [1147824000000,65.26],
  [1147910400000,63.18],
  [1147996800000,64.51],
  [1148256000000,63.38],
  [1148342400000,63.15]
]

I suspect this is why the data is not rendering. Why the difference in output and how can I return a response that highcharts will understand.

  • 写回答

2条回答 默认 最新

  • doushifen4060 2014-05-28 14:34
    关注

    It looks like the problem is with the data source (model data result).

    Check this out, if you prepared the data like this:

    $data[] = array(1317423600,0);
    $data[] = array(1325289600, -0.17099521359192);
    $data[] = array(1333148400, 0.85133638321359);
    
    var_dump(json_encode($data));
    

    it produces the json in the format you want:

    string '[[1317423600,0],[1325289600,-0.17099521359192],[1333148400,0.85133638321359]]' (length=77)
    

    So... to fix this, can could try something like this:

    Route::get('api/v1/data/{id}', function($id)
    {
        // Load DB Data
        $data = Model::getData($id);    
    
        // Parse Data
        $parsedData = array();
        foreach ($data as $k => $v)
            $parsedData[] = array($k, $v);
    
        // Finish
        return $parsedData;
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 电脑开机过商标后就直接这样,求解各位
  • ¥15 mysql , 用自己创建的本地主机和用户名 登录不上
  • ¥15 关于#web项目#的问题,请各位专家解答!
  • ¥15 vmtools环境不正常
  • ¥15 请问如何在Ubuntu系统中安装使用microsoft R open?
  • ¥15 jupyter notebook
  • ¥30 informer时间序列预测
  • ¥20 SSR引物多态性分析
  • ¥15 大漠插件在Win11易语言注册调用和免注册灵异事件,VS上注册调用完全没问题
  • ¥15 Addressable缓存机制做热更新的问题