Reputation: 879
$_SESSION['consequnce1']=[1,2,3]
$consequenceStr1=implode( ',', $_SESSION['consequence1']); //for storage to databases
$_SESSION['consequence1']=explode(',', $consequence1);
//$_SESSION['consequence1'] now is like["1","2","3"].
in html, I want get the array[1,2,3].
var sess = JSON.parse("<?php echo json_encode($_SESSION['consequence1']); ?>");
var num =sess[0];
but this two line code does not work, what's the problem? thanks
Answer: do not know the reason in fact. But just change
var sess = <?php echo json_encode($_SESSION['consequence1']); ?>;
then it works. Thanks for others' reply
Upvotes: 0
Views: 103
Reputation: 22683
That is, because json_encode
provides value that can be used directly in JavaScript. It wraps strings in double quotes and takes care of other types to be valid as well. JSON.parse
takes string as an argument, which is not necessary.
In your example, you had messed double quotes, like this:
JSON.parse("["1","2","3"]")
Upvotes: 1