简体   繁体   English

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

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

I know this has been asked plenty of times before but still I have a problem after readaing all the other posts on the subject... Somewhere between my php code -and the javascript it is sitting in- my array is going awol. 我知道这已经被问过很多次了,但是在重新阅读了该主题的所有其他帖子之后,我仍然遇到问题...在我的PHP代码和它所位于的javascript之间的某个地方,我的数组异常了。

In the attached code, I have an echo for debugging of the php. 在所附的代码中,我对php进行了调试。 When I cut out the php section from the javascript and run it separately with the echo on, it shows me that it is building my json_encoded array correctly. 当我从javascript中切出php部分并在echo上单独运行它时,它显示出它正在正确构建我的json_encoded数组。

In the javascript immediately after the php end I assign the php to a javascript variable, so I can use it for further processing (plotting a graph). 在php结束后的javascript中,我将php分配给了javascript变量,因此可以将其用于进一步处理(绘制图形)。 Putting in display statements, to display the content of the result of the php call to get the array into javascript, shows the array is empty. 放入display语句,以显示将数组放入javascript的php调用结果的内容,显示数组为空。

If I cut and paste the output of the php echo and assign this literal to the javascript chartData array then everything works fine. 如果我剪切并粘贴php echo的输出并将此文字分配给javascript chartData数组,则一切正常。 Why is the javascript not getting the php array content? 为什么JavaScript无法获取php数组内容?

Here's the code snip: 这是代码片段:

<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: The output of the print_r is: Array ( [0] => Array ( [week] => 1301 [Accepted] => 30 [Failed] => 5 [Passed] => 20 [Planned] => 5 [Skipped] => 5 [Unknown] => 26 ) [1] => Array ( [week] => 1302 [Accepted] => 25 [Failed] => 2 [Passed] => 25 [Planned] => 2 [Skipped] => 3 [Unknown] => 20 ) [2] => Array ( [week] => 1303 [Accepted] => 26 [Failed] => 26 [Passed] => 29 [Planned] => 26 [Skipped] => 26 [Unknown] => 10 ) ) @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: This is the jscript code immediately after the php (It is commented out because I tried lots of different options that were recommended in other posts in this forum and others - none of them work. I can run the php code and that works fine. If I copy the output of the echo in the php code snip I posted earlier and simply assign that to chartData (ie: chartData = ""; my chart is produced fine. The problem is not with the charting tool but somehow the array content is just not visible to the javascript which is directly below it in the .js file. Thanks for your time up til now. @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

UPDATE: I think there's something fundamentally wrong going on at my side. 更新:我认为我这边有些根本上的错误。 I used a very simple example which should write "hello world" to the screen but it returns nothing at all. 我使用了一个非常简单的示例,该示例应该在屏幕上写出“ hello world”,但它什么也不返回。 If I substitute the 'write' with an 'alert' then it still shows nothing in the alert popup. 如果我将“ write”替换为“ alert”,则在警报弹出窗口中仍不显示任何内容。 Does anyone know why this would not be working? 有谁知道为什么这不起作用? The code is: 代码是:

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