【问题标题】:Ajax canvas chart doesn't display changest?Ajax 画布图表不显示更改?
【发布时间】:2018-05-09 04:16:44
【问题描述】:

大家好,我对如何正确显示此动态图表有疑问。

此代码是当我选择类别和日期时,图表将根据每个选择的值而变化 下拉类别和日期过滤器:

<form class="form-inline" method='get'>
  <div class="form-group">

        <select name="category" id="category" onchange="showCategory(this.value)">
        <option value="ACCOUNT REGISTER" >ACCOUNT REGISTER</option>
        <option value="ACCOUNT UNREGISTER" >ACCOUNT UNREGISTER</option>
        <option value="CATEGORY 1">CATEGORY 1</option>
        <option value="CATEGORY 2">CATEGORY 2</option>
        <option value="CATEGORY 3">CATEGORY 3</option>
        </select>
    </div>
    <div class="form-group">
        <input class="form-control" id="monthx" type="month" name="monthx" onchange="filter_datex(this.value)">
    </div>

  <select class="form-control input-sm" id="chartType" name="Chart Type">
    <option value="line">Line</option>
    <option value="column">Column</option>
    <option value="bar">Bar</option>
    <option value="pie">Pie</option>
    <option value="doughnut">Doughnut</option>
  </select>  
    <div class="form-group">
        <a class="btn btn-primary pull-right" onclick="printDoc()"  target="_blank" >PRINT</a>
    </div>

</form>

渲染后的图表会转到这里的代码!

图表:

  <div  id="printDiv" >
    <div id="displayChart">
    <script>
    window.onload = function() {

    var chart = new CanvasJS.Chart("chartContainer", {
      animationEnabled: true,
      title: {
        text: "First Default Chart Before Onchange"
      },
      data: [{
        type: "pie",
        startAngle: 240,
        yValueFormatString: "##0.00'%'",
        indexLabel: "{label} {y}",
        dataPoints: [
          {y: 79.45, label: "Student"},
          {y: 7.31, label: "Admin"},
          {y: 7.06, label: "Teacher"}
        ]
      }]
    });
    chart.render();
    var chartType = document.getElementById('chartType');
    chartType.addEventListener( "change",  function(){
      chart.options.data[0].type = chartType.options[chartType.selectedIndex].value;
      chart.render();
    });

    }
    </script>

  </div>
</div>

我使用@Krishnadas PC 之前的答案代码,然后这是我的 JavaScript,现在标题正在更改

JSCRIPT:

<script type="text/javascript">
  function getDate(){
    var monthx =document.getElementById('monthx').value;

  }
  function getCategory(){
    var category =document.getElementById('category').value;

  }
  function printDoc(){
    var getCategory = getCategory();
    var getDate = getDate();
    window.location='assets/lib/FPDF/print?category='+getCategory+'&date='+getDate;

  }
  $('#monthx').hide();
  function showCategory(str) {
  var xhttp; 
  if (str == "") {
    document.getElementById("displayChart").innerHTML = "";
    return;
  }
  if (str == "ACCOUNT REGISTER" || str == "ACCOUNT UNREGISTER" || str == "default") {
    $('#monthx').hide();
  }
  else{
    $('#monthx').show();
  }
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {


                    var json_datax = this.responseText;
                    var monthx =document.getElementById('monthx').value;
                    var category =document.getElementById('category').value;

                    console.log(this.responseText)
                    var chart=new CanvasJS.Chart("chartContainer", {
                        animationEnabled: true, title: {
                            text: ''+category+" "+monthx+''
                        }
                        , data: [ {
                            type: "pie", startAngle: 240, yValueFormatString: "##0.00'%'", indexLabel: "{label} {y}", dataPoints: 
                            [ {
                                y: 79.45, label: 3123
                            }
                            , {
                                y: 7.31, label: "x"
                            }
                            , {
                                y: 7.06, label: "Baidu"
                            }
                            , {
                                y: 4.91, label: "Yahoo"
                            }
                            , {
                                y: 11.26, label: "Others"
                            }
                            ]
                        }
                        ]
                    }
                    );
                    chart.render();
                    var chartType=document.getElementById('chartType');

                    chartType.addEventListener( "change", function() {
                        chart.options.data[0].type=chartType.options[chartType.selectedIndex].value;
                        chart.render();
                    }
                    );
                }
            };
  xhttp.open("GET", "chart_ajax.php?category="+str+"&date="+monthx, true);
  xhttp.send();
}

  function filter_datex(str) {
  var xhttp; 
  if (str == "") {
    document.getElementById("displayChart").innerHTML = "";
    return;
  }
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    var json_datax = this.responseText;
                    var monthx =document.getElementById('monthx').value;
                    var category =document.getElementById('category').value;
                    console.log(this.responseText)
                    var chart=new CanvasJS.Chart("chartContainer", {
                        animationEnabled: true, title: {
                            text: ''+category+" "+monthx+''
                        }
                        , data: [ {
                            type: "pie", startAngle: 240, yValueFormatString: "##0.00'%'", indexLabel: "{label} {y}", dataPoints: 
                            [ {
                                y: 79.45, label: 3123
                            }
                            , {
                                y: 7.31, label: "x"
                            }
                            , {
                                y: 7.06, label: "Baidu"
                            }
                            , {
                                y: 4.91, label: "Yahoo"
                            }
                            , {
                                y: 11.26, label: "Others"
                            }
                            ]
                        }
                        ]
                    }
                    );
                    chart.render();
                    var chartType=document.getElementById('chartType');

                    chartType.addEventListener( "change", function() {
                        chart.options.data[0].type=chartType.options[chartType.selectedIndex].value;
                        chart.render();
                    }
                    );
                }
            };
  xhttp.open("GET", "chart_ajax.php?category="+monthx+"&date="+str, true);
  xhttp.send();
  }

</script>

然后在我的ajax页面中,类别和日期值将在页面上的POST然后GET[]变量使用get方法并基于get值执行查询,查询结果将作为json或echo作为一个完整的json代码,

CHART_AJAX.php

include('db.php');
$category = $_GET['category'];
//$category_ID =  $_GET['category_ID'];
$date = $_GET['date'];
$sql = "MY QUERY $date and $category";
$result = $con->query();
$row = $result->fetch_assoc();

$data  = json_encode($row['json']);

print_r ($data);
//result or print_r ($data)
//[ {
//    y: 79.45, label: 3123
//}
//, {
//    y: 7.31, label: "x"
//}
//, {
//    y: 7.06, label: "Baidu"
//}
//, {
//    y: 4.91, label: "Yahoo"
//}
//, {
//    y: 11.26, label: "Others"
//}
//]

我想要的是 chart_ajax.php 中 print_r 的结果必须传递给 js var 而不是 var json_data = //然后传递ajax_chart.php结果

data: [ {
    type: "pie", startAngle: 240, yValueFormatString: "##0.00'%'", indexLabel: "{label} {y}", dataPoints: 
    //this var json_data will be go here or else 
    //the result of ajax_chart.php must be go here !!! directly? 
}
]

然后我想在打印按钮是,当我点击它必须进入新标签,如 target="_BLANK" 而不是 SELF 窗口位置?

    function getDate(){
        var monthx =document.getElementById('monthx').value;

      }

  function getCategory(){
    var category =document.getElementById('category').value;

  }
  function printDoc(){
    var getCategory = getCategory();
    var getDate = getDate();
    window.location='assets/lib/FPDF/print?category='+getCategory+'&date='+getDate;

  }

【问题讨论】:

  • 更改监听器是否正常工作?通常在 js 库中,一旦从服务器端进行更改,您需要重新初始化它们。 onload 函数将不会在 ajax 响应之后运行。您可能需要在 ajax 响应之后使用新数据重新初始化图表,然后它可能会起作用。无法通过移动设备检查代码。
  • @krishnadas 我不知道如何解决这个问题 :( 。但是当发生变化时另一个变量仍在变化。嗯 .. 但图表没有呈现变化

标签: javascript php ajax canvas


【解决方案1】:

我不明白你想通过使用 ajax 来实现什么。 $_GET 中只有一个标题。您只能从 ajax 文件中返回它。其余代码可以在 ajax 响应部分中。这些更改将起作用。我这里测试过了。

chart_ajax.php

   <?php echo $title=$_GET['q'];

在实际应用程序中,您可以从数据库或其他第三方 API 中获取图形的值,并仅以 json 格式返回数据。无需渲染 html 并循环这些数据并在客户端(浏览器)端构建更新的图形。

在您的主文件中,像这样更新 ajax 响应部分。

xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("displayChart").innerHTML = this.responseText;
                    console.log(this.responseText)
                    var chart=new CanvasJS.Chart("chartContainer", {
                        animationEnabled: true, title: {
                            text: '"'+this.responseText+'"'
                        }
                        , data: [ {
                            type: "pie", startAngle: 240, yValueFormatString: "##0.00'%'", indexLabel: "{label} {y}", dataPoints: [ {
                                y: 79.45, label: 3123
                            }
                            , {
                                y: 7.31, label: "Bing"
                            }
                            , {
                                y: 7.06, label: "Baidu"
                            }
                            , {
                                y: 4.91, label: "Yahoo"
                            }
                            , {
                                y: 11.26, label: "Others"
                            }
                            ]
                        }
                        ]
                    }
                    );
                    chart.render();
                    var chartType=document.getElementById('chartType');
                    chartType.addEventListener( "change", function() {
                        chart.options.data[0].type=chartType.options[chartType.selectedIndex].value;
                        chart.render();
                    }
                    );
                }
            };

这些更改将更新图表,但这不会成为真正的应用程序。

【讨论】:

  • 我使用此代码及其工作以及更新我的帖子,我想要实现的是创建一个动态图表和 2 个下拉列表将负责类别和日期并将它们的值发送到 Ajax_file ,则ajax_file的结果将像{ y: 7.06, label: "Baidu" } , { y: 4.91, label: "Yahoo" }一样抛出json_data来动态改变图表值
  • 您在 ajax 响应中拥有所有必需的数据。从 this.responseText 构建图表对象。我建议您在实际尝试之前先学习基础知识。
  • 所以 ajax_file 的整个结果将转到 this.responseText 然后我尝试将其存储到 1 个变量然后将变量放在数据中心:图表中的 [],然后它仍然无法正常工作
  • 只有当您按照示例代码中提到的所需格式构建对象时,它才会起作用。我目前来自移动设备,无法进行编码。你得到正确的ajax响应了吗?如果这是正确的,您可以轻松构建该对象。首先尝试学习如何创建对象。 javascript.info 是一个很好的来源。
  • 啊好吧,我现在没有稳定的网络,我知道如何理解对象,也许我只是使用了错误的方法,嗯,
猜你喜欢
  • 2021-06-06
  • 1970-01-01
  • 2014-08-16
  • 2014-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-25
  • 1970-01-01
相关资源
最近更新 更多