繁体   English   中英

使用json_encode传递用于javascript的php数组

[英]Passing php array for use in javascript using json_encode

我知道这已经被问过很多次了,但是在重新阅读了该主题的所有其他帖子之后,我仍然遇到问题...在我的PHP代码和它所位于的javascript之间的某个地方,我的数组异常了。

在所附的代码中,我对php进行了调试。 当我从javascript中切出php部分并在echo上单独运行它时,它显示出它正在正确构建我的json_encoded数组。

在php结束后的javascript中,我将php分配给了javascript变量,因此可以将其用于进一步处理(绘制图形)。 放入display语句,以显示将数组放入javascript的php调用结果的内容,显示数组为空。

如果我剪切并粘贴php echo的输出并将此文字分配给javascript chartData数组,则一切正常。 为什么JavaScript无法获取php数组内容?

这是代码片段:

<script>
...some java script stuff;
<?php
// Define the mySQL db connection
$db = new PDO('mysql:host=localhost;dbname=remets;charset=UTF-8', 'remets', 'remets',         array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
// Define SQL query to fetch data from mySQL
$stmt = $db->query("SELECT WeekNumber,XAxisCategory,YAxisValue FROM Metric WHERE ReportID = 'Q3' ORDER BY WeekNumber,XAxisCategory ASC");

                                // declarations
                                $amData = array();
                                $amArray = array();
                                $ctrinner = 0;
                                $ctrouter = -1;
                                $prevweek = "9999";

                                // Fetch data from mySQL and put it in an array in the format we need
                                while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                    if ($prevweek !== $row['WeekNumber']) {
                                        $ctrouter++;
                                        $ctrinner = 0;
                                        $amData[$ctrouter]["week"] = "".$row['WeekNumber'];  // Prepending (or appending) the empty string makes the json encoding think the week number is a string, which is MUST have for AmCharts
                                  }
                                    $ctrinner++;
                                    $amData[$ctrouter][$row['XAxisCategory']] = $row['YAxisValue'];
                                    $prevweek = $row['WeekNumber'];
                                }

                                    // Using json_encode puts the data into an array format that we can use in a javascript
                                    $amJSONArray = json_encode($amData);

                                    // Echo is for debugging only.
                                    // echo $amJSONArray;


                            ?>

                            var chartData = <?php echo $amJSONArray; 
?>;

...more javascript stuff;

</script>

@Mahdi:print_r的输出为:Array([0] => Array([week] => 1301 [Accepted] => 30 [Failed] => 5 [Passed] => 20 [Planned] => 5 [ [跳过] => 5 [未知] => 26)[1] =>数组([周] => 1302 [接受] => 25 [失败] => 2 [通过] => 25 [计划中] => 2 [ [跳过] => 3 [未知] => 20)[2] =>数组([周] => 1303 [接受] => 26 [失败] => 26 [通过] => 29 [计划中] => 26 [已跳过] => 26 [未知] => 10))

@Mahdi:这是php之后的jscript代码(被注释掉是因为我尝试了许多其他选项,这些选项在该论坛的其他帖子以及其他文章中都被推荐-它们都不起作用。我可以运行php代码并且可以如果我在我之前发布的php代码片段中复制回显的输出,然后将其分配给chartData(即:chartData =“”;我的图表就很好了。问题不在于图表工具,而是数组)内容对.js文件中位于其正下方的javascript不可见,感谢您的宝贵时间。

                            //var chartData = "<?php print($amJSONArray); ?>";  // This just returns the literal in the speech marks
                            //var chartData = '<?php print($amJSONArray); ?>';  // This also returns the literal in the speech marks
                            //var chartData = "<?php echo($amJSONArray); ?>";   // This just returns the literal in the speech marks
                            //var chartData = '<?php echo($amJSONArray); ?>';   // This also returns the literal in the speech marks
                            //var chartData = <?php echo ($amJSONArray) ?>;     // This returns empty
                            //var chartData = <?php echo $amJSONArray ?>;       // This returns empty
                            //var chartData = (<?php echo $amJSONArray ?>);     // This returns empty
                            //alert(chartData);                                                                 // Returns empty - just showing the contents of the array if I do the json_encode within the php part
                            //alert(<?php echo $amJSONArray ?>);                                // Returns empty - just showing the contents of the array if I do the json_encode during the array fetch

更新:我认为我这边有些根本上的错误。 我使用了一个非常简单的示例,该示例应该在屏幕上写出“ hello world”,但它什么也不返回。 如果我将“ write”替换为“ alert”,则在警报弹出窗口中仍不显示任何内容。 有谁知道为什么这不起作用? 代码是:

<?php
   $testvar = "Hello World";
?>
<html>
<head>
<script type="text/javascript">
function hello()
 {
   // create JavaScript variable, fill it with Php variable
   var testvar = "<? print $testvar; ?>";
  // output to screen

   document.write( testvar );   
 } 
</script>
</head>

<!-- Call JavaScript function to display variable -->
<body onload="hello()" >
</body>
</html>  

如果您能够以字符串形式访问数据,则可以尝试使用内置的JSON.parse()将其转换为可用的javascript。

暂无
暂无

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

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