使用json_encode传递php数组以在javascript中使用

时间:2013-04-21 12:43:07

标签: php javascript json

我知道之前已经被问过很多次了但是在读完主题上的所有其他帖子之后我仍有问题...介于我的php代码之间的某个地方 - 和它坐在我的数组中的javascript正在进行中

在附加的代码中,我有一个用于调试php的echo。当我从javascript中删除php部分并单独使用echo运行它时,它向我显示它正在构建我的json_encoded数组。

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

如果我剪切并粘贴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] =&gt; Array([week] =&gt; 1301 [Accepted] =&gt; 30 [Failed] =&gt; 5 [Passed] =&gt; 20 [计划] =&gt; 5 [跳过] =&gt; 5 [未知] =&gt; 26)[1] =&gt;数组([周] =&gt; 1302 [已接受] =&gt; 25 [失败] =&gt ; 2 [通过] =&gt; 25 [计划] =&gt; 2 [跳过] =&gt; 3 [未知] =&gt; 20)[2] =&gt;数组([周] =&gt; 1303 [已接受] = &gt; 26 [失败] =&gt; 26 [通过] =&gt; 29 [计划] =&gt; 26 [跳过] =&gt; 26 [未知] =&gt; 10))

@Mahdi:这是php之后的jscript代码(它被注释掉,因为我尝试了很多不同的选项,这些选项在本论坛的其他帖子和其他帖子中推荐 - 它们都不起作用。我可以运行php代码如果我在之前发布的php代码片段中复制echo的输出,只需将其分配给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”,但它根本不返回任何内容。如果我用'alert'替换'write',那么它仍然不会在警告弹出窗口中显示任何内容。有谁知道为什么这不起作用?代码是:

<?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>  

1 个答案:

答案 0 :(得分:1)

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