如何获取Session值,该值是JavaScript中的一个数组


How to get Session value which is an array in JavaScript?

我在php页面中设置了一个会话,其中存储了如下数组:

首页.php

   $_SESSION["Counts"]=$some_array;
   echo print_r($_SESSION["Counts"]); 

输出:

Array ( [Finance] => Array ( [0] => 0 [1] => 3 [2] => 0 [3] => 0 [4] => 1 ) 
[Human resources] => Array ( [0] => 1 [1] => 5 [2] => 1 [3] => 0 [4] => 0 )
[Infrastructure] => Array ( [0] => 0 [1] => 3 [2] => 1 [3] => 0 [4] => 0 ) ) 1

正在.js页面中检索会话数据SecondJSpage.js

<script type="text/javascript">
var sessionValue= new Array();
var s= new Array();
var s1= new Array();
sessionValue = '<?php $_SESSION["Counts"]; ?>';
document.write(sessionValue);   //Does not output anything
for( s1 in sessionValue) {
for( s in s1) {
    document.write(s);     //Does not output anything
    document.write("<br />");
}}
</script>

只有数组未被检索。将显示一个简单的会话变量。如何解决这个问题?

稍微更改一下这一行。。

sessionValue = <?php echo json_encode($_SESSION["Counts"]); ?>;

为此使用json_encode()(Javascript可以处理JSON)。

查看手册:http://php.net/json_encode

不能echo数组。

<?php echo $_SESSION["Counts"]; // this is an array ?>

您也不能在.js文件中执行PHP(尝试在SecondJSpage.js中解析PHP)