I am using JSON in PHP, and now I need to access it from JavaScript. How do I pass a JSON object to JavaScript?
<?php
$array = array("a"=>"Caucho", "b"=>"Resin", "c"=>"Quercus");
$json = json_encode($array);
>
where My.js has:
showAll(){
alert("Show All Json Objects");
// How do I get the JSON value here?
}
How can I do it?
Assuming that you're using Ajax as your method to download the JSON, you would echo the result of the json_encode:
<?php
$array = array("a"=>"Caucho", "b"=>"Resin", "c"=>"Quercus");
echo json_encode($array);
?>
And then within your call back event, you'd eval the response:
var obj = eval('(' + req.ResponseText + ')');
for(var i in obj) {
alert(i + ': ' + obj[i]);
}
Assuming that you have an XMLHttpRequest object with the name req.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With