简体   繁体   English

JavaScript json_encode中的PHP数组不起作用

[英]PHP array in javascript json_encode not working

I have a php page that connects to mysql database, performs a query, stores its result as an array as a session variable. 我有一个连接到mysql数据库的php页面,执行查询,并将其结果作为数组存储为会话变量。

$_SESSION['array1']=$array1;

This variable is received by another php page within same directory like this: 相同目录下的另一个php页面会收到此变量,如下所示:

session_start();
$array1= $_SESSION['array1'];

Now, in the same php page itself, I have a javascript code that intends to access this $array1 and print its value. 现在,在同一个php页面中,我有一个javascript代码,打算访问此$ array1并打印其值。 I found similar questions online and got to know about json_encode function but couldn't get it done. 我在网上发现了类似的问题,并且了解json_encode函数,但无法完成。 Code: 码:

<script type="text/javascript">
var jsarray= <?php json_encode($array1); ?>;
document.write (jsarray[2]);   </script>

I am just trying to print the 2nd index of array through javascript but haven't been able to do so. 我只是想通过javascript打印数组的第二个索引,但还没有做到这一点。 Nothing is displayed at all. 什么都没有显示。 I can see that I can print array on the second page using php but I need javascript code to be able to access the array. 我可以看到我可以使用php在第二页上打印数组,但是我需要JavaScript代码才能访问该数组。 If I provide values to jsaraay in javascript code like: 如果我在javascript代码中为jsaraay提供值,例如:

var jsarray=[1,2,3,4,5];

and i print 2nd index, 我打印第二索引,

document.write(jsarray[2]);

The output is correct. 输出正确。 I want to access php array the same way. 我想以相同的方式访问php数组。 Please help? 请帮忙?

You need to echo the json: 您需要echo显json:

var jsarray= <?php echo json_encode($array1); ?>;

Online sample here . 在线样本在这里

If i write 如果我写

$array = [1, 2, 3];
print('<script> jsarray = ' . json_encode($array) . ';</script>');

then I can access jsarray in my javascript. 那么我可以在我的JavaScript中访问jsarray

Note that jsarray[2] wil return the 3rd index, not the 2nd (indices start at 0). 请注意, jsarray[2]返回第三个索引,而不是第二个索引(索引从0开始)。 You can also check your javascript console (F12 on Chrome + Firefox, then select console tab) for errors. 您还可以检查JavaScript控制台(在Chrome + Firefox上为F12,然后选择控制台选项卡)是否有错误。

try this way: 尝试这种方式:

<script>
var jsArray = ["<?php echo join("\", \"", $array1); ?>"];
alert(jsArray);
</script>

That should work 那应该工作

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

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