简体   繁体   English

从 JQUERY/AJAX 到 Morris.JS 的数据

[英]Data from JQUERY/AJAX to Morris.JS

I'm trying to export data from AJAX/JQUERY to Morris.JS.我正在尝试将数据从 AJAX/JQUERY 导出到 Morris.JS。

Variable datachart return with data.可变数据图表返回数据。 but morris.js graph returns no Line/bar但 morris.js 图不返回 Line/bar

            $("#diseaseselection").change(function(){
                $("#chart").empty();
                var diseaseselection = $("#diseaseselection").val();
                $.ajax({
                    url: "chart.php",
                    method: "POST",                   
                    data: {
                        diseaseselection: diseaseselection
                    },
                    success: function(data) {
                        Morris.Line({
                            element : 'chart',
                            data:[data],
                            xkey:'age',
                            ykeys:[ 'totalM', 'totalF'],
                            labels:['Total MALE', 'Total FEMALE'],
                            hideHover:'auto',
                            pointStrokeColors: ['white'],
                            lineWidth:'6px',
                            parseTime: false,
                            lineColors: ['Skyblue', 'Pink'],
                        });
                    }

                });
            });

Here is my sample PHP code Please help me how to figure it out i badly need it thanks alot man.这是我的示例 PHP 代码请帮助我如何弄清楚我非常需要它,非常感谢。 already trying my best已经尽力了

$diseaseselection = $_REQUEST['diseaseselection'];

if(isset($diseaseselection)){ 
   $result = mysqli_query($con, "SELECT disease,age,SUM(CASE WHEN gender = 'm' THEN 1 ELSE 0 END) AS totalM, SUM(CASE WHEN gender = 'f' THEN 1 ELSE 0 END) AS totalF FROM mdr where disease = '$diseaseselection' GROUP BY disease , age"); 
   $chart_data = ''; 

while($row = mysqli_fetch_array($result)) { 
      $chart_data .= "{ age:'".$row["age"]."', totalM:".$row["totalM"].", totalF:".$row["totalF"]."}, "; 
} 
$chart_data = substr($chart_data, 0, -2); 
echo $chart_data; }

Here is my sample Output This is based on my console log console.log(data);这是我的示例输出这是基于我的控制台日志 console.log(data); Please help me how to figure it out i badly need it thanks alot man.请帮助我如何弄清楚我非常需要它,非常感谢。 already trying my best已经尽力了

{ age:'0-1', totalM:2, totalF:1},

{ age:'1-4', totalM:1, totalF:0},

{ age:'10-14', totalM:0, totalF:1},

{ age:'15-19', totalM:0, totalF:1},

{ age:'5-9', totalM:0, totalF:3},

{ age:'55-59', totalM:6, totalF:0}

There are a number of little issues here, which are kind of all tied up in the same key problem - what your PHP is producing is not valid JSON data.这里有许多小问题,它们都与同一个关键问题有关 - 您的 PHP 生成的不是有效的 JSON 数据。

If you copy and paste your sample data into a validator such as JSONLint you'll that it fails in a couple of ways:如果您将示例数据复制并粘贴到JSONLint等验证器中,您会发现它在以下几种情况下会失败:

1) You've got a list of objects, but in order to be a valid list (or array , as it's usually known) the items must be wrapped in square brackets ( [ and ] ) at the beginning and end. 1) 你有一个对象列表,但为了成为一个有效的列表(或数组,正如它通常所知),这些项目必须在开始和结束时用方括号( [] )括起来。

2) The property names (eg age, totalM, and totalF) must have double quote marks ( " ) around them. 2) 属性名称(例如age、totalM 和totalF)必须用双引号( " ) 括起来。

3) The string values (eg 0-1, 1-4 etc) must have double quote marks around them, not single quote marks. 3) 字符串值(例如 0-1、1-4 等)周围必须有引号,而不是单引号。

A valid version of your sample JSON would look like this:示例 JSON 的有效版本如下所示:

[
  { "age": "0-1", "totalM": 2, "totalF": 1 }, 
  { "age": "1-4", "totalM": 1, "totalF": 0 }, 
  { "age": "10-14", "totalM": 0, "totalF": 1 }, 
  { "age": "15-19", "totalM": 0, "totalF": 1 }, 
  { "age": "5-9", "totalM": 0, "totalF": 3 }, 
  { "age": "55-59", "totalM": 6, "totalF": 0 }
]

You might find this tutorial useful as a quick way to learn the syntax.您可能会发现本教程作为一种快速学习语法的方法很有用。

However, useful as it is to know the syntax, you don't actually have to create it manually via your PHP, as you are doing now.但是,虽然了解语法很有用,但实际上您不必像现在一样通过 PHP 手动创建它。 In fact that's quite a bad idea to do that, because it leaves you vulnerable to silly mistakes (like not adding the square brackets), and at risk of accidental syntax errors in the JSON (eg imagine one of your string values itself contained a double-quote mark: if you didn't use a suitable escape character in front of it, then in the JSON it would look like the end of the property, and what followed would then be invalid).事实上,这样做是一个非常糟糕的主意,因为它让你容易犯愚蠢的错误(比如没有添加方括号),并且有在 JSON 中出现意外语法错误的风险(例如想象你的一个字符串值本身包含一个双-quote mark:如果你没有在它前面使用合适的转义字符,那么在 JSON 中它看起来像属性的结尾,后面的内容将是无效的)。

The result of the problems above is that your PHP returns a string of invalid data back to the browser, and that cannot be used to populate the chart.上述问题的结果是您的 PHP 将一串无效数据返回给浏览器,并且无法用于填充图表。

It's far better to simply construct a normal array in PHP, and then use the built-in json_encode() function to take care of turning that object into valid JSON.最好在 PHP 中简单地构造一个普通数组,然后使用内置的json_encode()函数来处理将该对象转换为有效的 JSON。 This is commonly accepted as best practice, and if you follow any introductory PHP/JSON tutorial it will show this function to you.这通常被认为是最佳实践,如果您遵循任何介绍性 PHP/JSON 教程,它将向您展示此功能。

To add to the problems creating the JSON server-side, there's a client-side issue too: even if you did return valid JSON, at that point it's still a string - in order for it to be used in your chart you'd have to parse it into a JavaScript variable.为了增加创建 JSON 服务器端的问题,还有一个客户端问题:即使您确实返回了有效的 JSON,此时它仍然是一个字符串 - 为了在您的图表中使用它,您将拥有将其解析为 JavaScript 变量。 If you specify dataType: "json" in your $.ajax options, jQuery will do the parsing for you automatically.如果您在$.ajax选项中指定dataType: "json" ,jQuery 将自动为您解析。 Otherwise, you would make a call to JSON.parse() to do it.否则,您将调用JSON.parse()来执行此操作。

Hopefully you see the overall pattern now - you take a PHP variable and turn it into JSON, which is a text representation of the data.希望您现在看到了整体模式 - 您将一个 PHP 变量转换为 JSON,它是数据的文本表示。 This allows you to send it across the internet.这允许您通过互联网发送它。 Then when it arrives at the destination, you turn it back into a (JavaScript) variable again to be used in the code.然后,当它到达目的地时,您将其再次转换回(JavaScript)变量以在代码中使用。

Here's some example PHP which will generate valid JSON in the recommended way.这是一些示例 PHP,它将以推荐的方式生成有效的 JSON。 I've added comments at important lines:我在重要的行添加了评论:

$diseaseselection = $_REQUEST['diseaseselection'];

if(isset($diseaseselection)){ 
   $result = mysqli_query($con, "SELECT disease,age,SUM(CASE WHEN gender = 'm' THEN 1 ELSE 0 END) AS totalM, SUM(CASE WHEN gender = 'f' THEN 1 ELSE 0 END) AS totalF FROM mdr where disease = '$diseaseselection' GROUP BY disease , age"); 
   $chart_data = array(); //declare an array, not a string. This will become the outer array of the JSON.

  while($row = mysqli_fetch_array($result)) { 
      //add a new item to the array
      //each new item is an associative array with key-value pairs - this will become an object in the JSON
      $chart_data [] = array(
        "age" => $row["age"], 
        "totalM" => $row["totalM"], 
        "totalF" => $row["totalF"]
      ); 
  } 

  $json = json_encode($chart_data);  //encode the array into a valid JSON object
  echo $json; //output the JSON
}

And here's the relevant part of the JavaScript code to receive it这是接收它的 JavaScript 代码的相关部分

$.ajax({
  url: "chart.php",
  method: "POST",
  data: {
    diseaseselection: diseaseselection
  },
  dataType: "json", //parse the response data as JSON automatically
  success: function(data) {
    Morris.Line({
      element: 'chart',
      data: data, //supply the response data (which is now a JS variable) directly, no extra brackets
      xkey: 'age',
      ykeys: ['totalM', 'totalF'],
      labels: ['Total MALE', 'Total FEMALE'],
      hideHover: 'auto',
      pointStrokeColors: ['white'],
      lineWidth: '6px',
      parseTime: false,
      lineColors: ['Skyblue', 'Pink'],
    });
  }
});

Here's a working demo of just the AJAX and chart part (using a dummy server to provide the JSON): https://jsfiddle.net/7o9ptajr/1/这是 AJAX 和图表部分的工作演示(使用虚拟服务器提供 JSON): https : //jsfiddle.net/7o9ptajr/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM