【问题标题】:PHP JSON variable in javascriptjavascript中的PHP JSON变量
【发布时间】:2014-01-27 21:07:26
【问题描述】:

我正在使用 php 生成 JSON“文本”,并希望将其包含在同一文件的 javascript 中。 我想我在理解 java 如何将 JSON 作为文本与作为对象处理时遇到了问题。

注意:我将很快将mysql更改为mysqli,只是想让这个东西先工作。 这是我的脚本:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Knox QA tickets status</title>
</head>
<body>
  <script src="am/amcharts/amcharts.js" type="text/javascript"></script>
  <script src="am/amcharts/serial.js" type="text/javascript"></script> 

<?php
    //$subm = "8";
    // This is being loaded from a selection html script 
    $subm =  $_POST["submoduleID"];
    if(!isset($_POST["submoduleID"]) )
    {
    // set it to the default container if it's not set.
     $subm = "8";
    }

    // Connect to MySQL
    $link = mysql_connect( 'localhost', 'root', 'secret' );
    if ( !$link ) {
      die( 'Could not connect: ' . mysql_error() );
    }

    // Select the data base
    $db = mysql_select_db( 'xqa_status', $link );
    if ( !$db ) {
      die ( 'Error selecting database \'test\' : ' . mysql_error() );
    }

    // Fetch the data
    $query = ("select date, tested, passed from test_status where xqa_id=" . $subm . " order by test_status_id limit 10");

    $result = mysql_query( $query );

    // Make a josn formatted output 
    $rows = array();
    while ( $r = mysql_fetch_assoc($result)) {
      $rows[] = $r;
    }
    $chartData_json = json_encode($rows);
    print $chartData_json;
    mysql_close($link);
?>


<!-- Custom Function  
  <script>
    AmCharts.loadJSON = function(file) {
      // create the request
      if (window.XMLHttpRequest) {
        // IE7+, Firefox, Chrome, Opera, Safari
        var request = new XMLHttpRequest();
      } else {
        // code for IE6, IE5
        var request = new ActiveXObject('Microsoft.XMLHTTP');
      }

      request.open('GET', file, false);
      request.send();

      // parse adn return the output
      return eval(request.responseText);
    };
  </script> -->


<!-- chart container -->
<div id="chartdiv" style="width: 600px; height: 300px;"></div>


<!-- the chart code -->
  <script>
    var chart;
    var chartData1 = "<?php echo $chartData_json; ?>";
    var myObject = JSON.parse(chartData1, reviver);
    // create chart
    AmCharts.ready(function() {

      // load the data
      // SERIAL CHART
      chart = new AmCharts.AmSerialChart();
      chart.pathToImages = "am/amcharts/images/";
      chart.dataProvider = myObject;
      chart.categoryField = "date";
      chart.dataDateFormat = "YYYY-MM-DD";

      // GRAPHS

      var graph1 = new AmCharts.AmGraph(); 
      graph1.type = "smoothedLine";
      graph1.title = "Tested";
      graph1.valueField = "tested";
      graph1.bullet = "round";
      graph1.bulletSize = 5;
      graph1.bulletBorderColor = "#FFFFFF";
      graph1.bulletBorderThickness = 2;
      graph1.lineThickness = 2;
      graph1.lineAlpha = 0.5;
      chart.addGraph(graph1);

      var graph2 = new AmCharts.AmGraph();
      graph2.type = "smoothedLine";
      graph2.title = "Passed";
      graph2.valueField = "passed";
      graph2.bullet = "round";
      graph2.bulletSize = 5;
      graph2.bulletBorderColor = "#FFFFFF";
      graph2.bulletBorderThickness = 2;
      graph2.lineThickness = 2;
      graph2.lineAlpha = 0.5;
      chart.addGraph(graph2);

      // CATEGORY AXIS
      chart.categoryAxis.parseDates = true;
      chart.categoryAxis.autoGridCount = false;
      chart.categoryAxis.gridCout = chartData.length;
      chart.categoryAxis.gridPosition = "start";
      chart.categoryAxis.labelRotation = 90;

      // LEGEND
      var legend = new AmCharts.AmLegend();
      chart.addLegend(legend);

       // CURSOR
       var chartCursor = new AmCharts.ChartCursor();
       chartCursor.cursorAlpha = 0;
       chartCursor.cursorPosition = "mouse";
       chartCursor.categoryBalloonDateFormat = "YYYY-MM-DD";
       chart.addChartCursor(chartCursor);

       // SCROLLBAR
       var chartScrollbar = new AmCharts.ChartScrollbar();
       chart.addChartScrollbar(chartScrollbar);

       // 3D
       // chart.angle = 30;
       // chart.depth3D = 15;



       // WRITE
       chart.write("chartdiv");



    });

  </script>

</body>
</html>

json 输出示例如下:

[{"date":"2014-01-09","tested":"12","passed":"32"},{"date":"2014-01-10","tested":"12","passed":"34"},{"date":"2014-01-11","tested":"22","passed":"34"},{"date":"2014-01-12","tested":"22","passed":"34"},{"date":"2014-01-13","tested":"40","passed":"34"},{"date":"2014-01-14","tested":"40","passed":"34"},{"date":"2014-01-15","tested":"40","passed":"34"}]

【问题讨论】:

  • 不太清楚.. 你的具体问题是什么?
  • 在一个文件中混合 javascript 和 php,哦,我的
  • 感谢 Patrick,这确实解决了我的问题,Javascript 无法将 JSON 理解为对象,因为它位于“双引号”内。

标签: javascript php json variables object


【解决方案1】:

您需要将 PHP 的输出分配给 Javascript 变量:

<script>
  var json_data=<?php

...

?>;

  // Do stuff with json_data
</script>

然后json_data 将是 Javascript 中的一个数组或对象(它不再是 JSON,因为 JSON 将被解析为数组文字,而不是字符串)。这很可能是您想要的,从那时起您就可以使用数组,例如 json_data[0].data。

【讨论】:

  • 不要忘记在您的 json 周围添加引号。最好写类似: var json_data="";
  • @mat,不,这会导致错误,因为 json 本身包含引号,所以当 javascript 加载它时,它会看到类似"{"somevar":"somevalue"}" 的东西并出错。 Paulpro 拥有它的方式,json 字符串将被视为对象文字。
  • 但我这里有变量: var chartData1 = "";双引号实际上是问题所在。
  • 只需使用 json_encode 和 json_decode 来打印 json ......它就像一个带有数组和处理转义引号等的魅力......
猜你喜欢
  • 2018-12-06
  • 2014-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
相关资源
最近更新 更多