doujia9204 2016-11-25 15:46
浏览 59

无法让谷歌图表从ajax工作,得到不是数组,当我直接回显数据时工作

first question but I have been coding PHP/HTML/JS etc for many years.

I have searched and googled for best of the day, I have found multiple answers on this topic here, however none of the solutions has helped in my case.

I use google charts to create a line graph over player ratings. - This works perfectly when I generate the data on the server and print it in the page directly. - If I call the server-side method with an ajax call to get the data, I'm getting the response "Uncaught error Not an array" in the console.

The data is as far as I can see, identical, the json validates in both cases, I have tried it with json_encode on the server and $.parseJSON in the javascript, and without in all combinations. No luck.

This is how I call it when that page adds the data to the call as I generate the page on the server, this works.

var data = google.visualization.arrayToDataTable(<?php echo $this->data['rating_data'] ?>);

Since I need to call this from a list of users, as you click on the users, I use an ajax call to get the data and call drawChart(iID) with javascript, this does not work:

function drawChart(iId) {
                var jsonData = $.ajax({
                      url: "xxxxxxxxxxx/getRatingForPlayer&playerId="+iId,
                      dataType: "json",
                      async: false
                }).responseText;

var data = google.visualization.arrayToDataTable($.parseJSON(jsonData));

(url above is anonymized of course) I have dumped what's in the jsonData in console & alerts and I am gettign the same, valid JSON reply from the server every time, paste that code hard into the call arrayToDataTable and it works, but not when it is placed in the variable jsonData.

If I change the above to var data = new google.visualization.DataTable(jsonData); now I don't get the error "not an array" any more, however, then I get the "table ahs no columns" error. Since the serverside response is the same for both my usecases, I don't really want to rewrite that if the syntax differs. I have tried to change the quotation of the returned string to use " inside instead of ' which does not help.

The data I return from the server-call is the same, regardless if I grab it as the page loads, or if it is through a serverside call. It looks like this (and yes, the date values are supposed to be empty except for start and end) I have validated it through JSONlint and it reports as valid JSON

"[['Session date','Player Rating'],['2016-10-01 00:00:00',1500],['',1519],['',1496],['',1508],['2016-11-11 16:20:39',1432]]"

The above string is generated like this on the server (just part of larger code of course):

public function getRatingForPlayer(){
    $playerId = $this->request->get['playerId'];
    $rating_data = $this->hov->api_user_getPlayerRatingHistory($playerId);
    $sRating = $this->mapChartString($rating_data);
    //$this->data['rating_data'] = json_encode($sRating, JSON_PRETTY_PRINT); 
    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($sRating, JSON_NUMERIC_CHECK));
}
public function mapChartString($data){      
    $last = sizeof($data['rating'])-1;
    $string = "[['Session date','Player Rating'],";
    foreach ($data['rating'] as $key => $value) {
        if( ($key == 0) || ($key == $last)){
            $date_string = $data['created'][$key];
        }else{
            $date_string = '';
        }
        $string .= "['".$date_string."',".$value."],";          
    }
    $string = rtrim($string, ",");
    $string .= "]";
    return $string;
}

As said above, output from this works perfectly when I use echo/print to put it into the page, but not as it comes from the ajax call and is placed in a js variable. This even as the returned data is visually identical and both validate.

I've even desperately tried remapping the json objects to an array before and/or after using $.parseJSON(jsonData) which obviously did not work at all.

So at this point I'm stumped. The question maps perfectly to this one: Google Chart - uncaught error: not an array and that's where I got the $.parseJSON(jsonData) from + the hints on properly encoding it on the server. But it does not help so I have to be missing something else here.

Very thankful for all and any help. /Dan

  • 写回答

1条回答 默认 最新

  • dthdlv9777 2016-11-25 16:25
    关注

    Naturally, as you post the question you start thinking differently around it. I solved it just after posting the Q.

    I did the following: Since the call to arrayToDataTable and the subsequent calls to draw the chart fires directly, it might not be populated form the ajax call yet. So I added a callback in the success-member of the ajax call and moved all the calls to that. This to make sure the ajax has actually returned something. Like this:

    function drawChart(iId) {
                    var jsonData = $.ajax({
                          url: "XXXXXXXXXXXX/getRatingForPlayer&playerId="+iId,
                          dataType: "json",
                          async: false ,
                          success: function(jsonData) {
                          var data = google.visualization.arrayToDataTable($.parseJSON(jsonData));
    
                            var options = {
                              backgroundColor: 'transparent',
                              colors:['#73B322'],
                              explorer: { actions: ['dragToZoom', 'rightClickToReset'] },
                              legend:{position: 'top', textStyle: {color: '#73B322', fontSize: 16}},
                              hAxis: {textStyle:{color: '#C9E093'}},
                              vAxis: {textStyle:{color: '#C9E093'}}
                            };
    
                            var chart = new google.visualization.LineChart(document.getElementById('rating_chart'));
    
                            chart.draw(data, options);
                          }
                    }).responseText;
    

    This then gave me a JSON error of an unexpected token, that was then solved in the PHP code to return " instead of ' for enclosing the strings inside the generated json.

    And now it all works as I expected it to. Hope the solution helps someone else. /Dan

    评论

报告相同问题?

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效