简体   繁体   中英

Unable to access PHP array in javascript, javascript object initialized to array ends up empty in chrome developer tools

I'm trying to get a JSON from PHP array so I can overlay the JSON on to a google charts geochart. So I am trying to get this working by using this simple code in test.php file

<?php 
  include("conn.php");
?>

<!DOCTYPE html>
<html>
<head>
  <title>test</title>
</head>
<body>

<script type="text/javascript">
  document.onload = function (){
    var jsonObj = <?php echo json_encode($rowarr, JSON_FORCE_OBJECT); ?>;
    var jsonString = JSON.stringify(jsonObj, null, '\n');
    console.log(jsonString);
  };

</script>
</body>
</html>

The conn.php file returns an array like so

{"Auckland":37616,"Wellington":35357,"Christchurch":29818}

But in the chrome developer tools I see that this code appears as

document.onload = function (){
var jsonObj = ;
    // Chrome error here -> Uncaught SyntaxError: Unexpected token ;
var jsonString = JSON.stringify(jsonObj, null, '\n');

The jsonObj variable is empty, when there should be something in it.

On the CDT console I get

Uncaught SyntaxError: Unexpected token ;

at line 11 in this test.php file

Chrome somtimes just doesn't show processable arrays and XMLs properly but they are exist. my advise: just dont test your codes on chrome before getting actual results on other Browsers.

I have encountered this kind of scenario yesterday.

<script type="text/javascript">
  document.onload = function (){
    var jsonObj = <?php echo json_encode($rowarr); ?>;
    var jsonString = JSON.parse(jsonObj);
    console.log(jsonString);
  };

</script>

Seems to me that $rowarr doesn't contain what you think it contains. Maybe try logging it first....

console.log("$rowarr");

You're along the right lines.

First of all, you can get rid of the enclosing document.onload as it's pointless.

Secondly, here's the amended code:

var jsonStringified = <?php echo json_encode($rowarr); ?>,
    jsonObject = JSON.parse(jsonStringified);

console.log(jsonObject);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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