[英]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. 我正在尝试从PHP数组获取JSON,以便可以将JSON覆盖到Google图表地理图表上。 So I am trying to get this working by using this simple code in test.php file
所以我试图通过在test.php文件中使用此简单代码来使此工作正常
<?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 conn.php文件返回一个像这样的数组
{"Auckland":37616,"Wellington":35357,"Christchurch":29818}
But in the chrome developer tools I see that this code appears as 但是在chrome开发人员工具中,我看到此代码显示为
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. 当应该包含jsonObj变量时,该变量为空。
On the CDT console I get 在CDT控制台上,我得到
Uncaught SyntaxError: Unexpected token ;
未捕获到的SyntaxError:意外令牌;
at line 11 in this test.php file 在此test.php文件的第11行
Chrome somtimes just doesn't show processable arrays and XMLs properly but they are exist. Chrome有时无法正确显示可处理的数组和XML,但它们确实存在。 my advise: just dont test your codes on chrome before getting actual results on other Browsers.
我的建议:在其他浏览器上获取实际结果之前,请不要在chrome上测试您的代码。
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. 在我看来,$ rowarr不包含您认为的内容。 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. 首先,您可以摆脱封闭的document.onload,因为它毫无意义。
Secondly, here's the amended code: 其次,这是修改后的代码:
var jsonStringified = <?php echo json_encode($rowarr); ?>,
jsonObject = JSON.parse(jsonStringified);
console.log(jsonObject);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.