简体   繁体   中英

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. This is my 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:

var dates = <?php echo json_encode($datesArray); ?>;
console.log(dates);

keeps giving dates back as null, and I am not sure why. I have tried encoding the array as utf-8, and I have tried using jQuery.parseJSON which also did not work.

Thanks--

Just checking, but is that JavaScript with PHP in a .js file? 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.

If that is the case, the easiest solution is to run that part of the script in some <script> tags.

Alternatively you could make Apache try to serve .js files as PHP file via Mime-Types; but that is really a mess not worth implementing.

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