dragon321723 2013-04-21 12:43
浏览 75

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

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.

In the attached code, I have an echo for debugging of the 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.

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). 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.

If I cut and paste the output of the php echo and assign this literal to the javascript chartData array then everything works fine. Why is the javascript not getting the php array content?

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: 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.

                            //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. If I substitute the 'write' with an 'alert' then it still shows nothing in the alert popup. 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>  
  • 写回答

1条回答 默认 最新

  • dongyang1518 2013-04-21 20:27
    关注

    If you are able to access the data as a string, you can try using the built-in JSON.parse() to convert it into usable javascript.

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号