簡體   English   中英

從Ajax請求中使用Json_encoded數組重繪Chart.js圖表

[英]Redraw Chart.js Chart with Json_encoded array from ajax request

我有一個使用chart.js庫繪制的圖表。 第一次繪制非常順利,但是我嘗試使用ajax調用中的NEW數據重繪甜甜圈圖。

我正在使用PHP和Codeigniter捕獲我需要的所有數據,並返回json_encoded數組以重繪該圖。 但是,如果我從控制台復制返回的代碼並將其粘貼到它中,它就不能與我當前的代碼一起使用,很好! 有人知道為什么嗎? 我也嘗試過JSON_FORCE_OBJECT並且它不起作用...

這是我的控制器代碼...

$data = array();
  foreach($g_data as $gd) {
    $temp = array(
        'value' => $gd['count'],
        'color' => $this->App_model->adjustBrightness($base_color),
        'label' => $gd['label']
    );
    array_push($data, $temp);
  }

  echo json_encode($data);

這是我的JS ...

$.ajax({
     type: "POST",
     url: siteUrl + "app/load_graph",
     data: {
      question_id: question_id
     },
     success: function(data) {

        //Get context with jQuery - using jQuery's .get() method.
        var ctx = $("#analytics-graph").get(0).getContext("2d");
        //This will get the first returned node in the jQuery collection.
        var myNewChart = new Chart(ctx);

        new Chart(ctx).Doughnut(data);

    } 
  });

這是我的php請求輸出到控制台的內容:

[{"value":3,"color":"#64ff9d","label":"less than 1"},{"value":0,"color":"#63ff9c","label":"2"},{"value":0,"color":"#71ffaa","label":"3"},{"value":0,"color":"#74ffad","label":"4"},{"value":2,"color":"#57ff90","label":"5"},{"value":0,"color":"#7cffb5","label":"6+"}]

而這就是讓我感到困惑的事情,如果我復制上面返回的對象並將其用作代碼中的變量,則效果很好! 不知道為什么...

$.ajax({
     type: "POST",
     url: siteUrl + "app/load_graph",
     data: {
      question_id: question_id
     },
     success: function(data) {

        //Get context with jQuery - using jQuery's .get() method.
        var ctx = $("#analytics-graph").get(0).getContext("2d");
        //This will get the first returned node in the jQuery collection.
        var myNewChart = new Chart(ctx);

        var data = [{"value":3,"color":"#64ff9d","label":"less than 1"},{"value":0,"color":"#63ff9c","label":"2"},{"value":0,"color":"#71ffaa","label":"3"},{"value":0,"color":"#74ffad","label":"4"},{"value":2,"color":"#57ff90","label":"5"},{"value":0,"color":"#7cffb5","label":"6+"}]

        new Chart(ctx).Doughnut(data);

    } 
  });

我是個白痴,只需要在jquery ajax函數中使用“ json”類型,這個問題可能對其他人很有用,所以這是它的解決方法:dataType:“ json”,

$.ajax({
     type: "POST",
     dataType: "json",
     url: siteUrl + "app/load_graph",
     data: {
      question_id: question_id
     },
     success: function(data) {

        //Get context with jQuery - using jQuery's .get() method.
        var ctx = $("#analytics-graph").get(0).getContext("2d");
        //This will get the first returned node in the jQuery collection.
        var myNewChart = new Chart(ctx);

        new Chart(ctx).Doughnut(data);

    } 
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM