[英]json_encode works in php, but null in javascript
I'm just learning php, and I am trying to parse some files I have, and then send the information to javascript. 我正在学习php,并且尝试解析一些文件,然后将信息发送到javascript。 This is my php: 这是我的PHP:
$datesArray = readFile();
echo json_encode($datesArray);
This echoes: 这呼应:
["120102000000","120102000500","120102001000","120102001500","120102002000","120102002500","120102003000"]
Which is what I want. 这就是我想要的。 However, my javascript, which looks like this: 但是,我的JavaScript看起来像这样:
var dates = <?php echo json_encode($datesArray); ?>;
console.log(dates);
keeps giving dates
back as null, and I am not sure why. 一直将dates
返回为null,但我不确定为什么。 I have tried encoding the array as utf-8, and I have tried using jQuery.parseJSON
which also did not work. 我尝试将数组编码为utf-8,并且尝试使用jQuery.parseJSON
也不起作用。
Thanks-- 谢谢 -
Just checking, but is that JavaScript with PHP in a .js
file? 只是检查,但是.js
文件中的JavaScript和PHP是吗? By default, Apache only runs PHP in files ending in .php
so that would mean your PHP is getting parsed as plain text by the server. 默认情况下,Apache仅在以.php
结尾的.php
运行PHP,这意味着服务器将您的PHP解析为纯文本。
If that is the case, the easiest solution is to run that part of the script in some <script>
tags. 如果是这种情况,最简单的解决方案是在某些<script>
标记中运行脚本的该部分。
Alternatively you could make Apache try to serve .js
files as PHP file via Mime-Types; 或者,您可以让Apache尝试通过Mime-Types将.js
文件作为PHP文件提供; but that is really a mess not worth implementing. 但这确实是一团糟,不值得实施。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.