简体   繁体   中英

php javascript place script in a file

I tried the following:

<script type="text/javascript>
  var cdata = <?php echo json_encode($cdata); ?>;
</script>

it works fine. I'm trying to place the script in a file:

var cdata = <?php echo json_encode($cdata); ?>;

and then access it with:

<script src="crewjs.php"   type="text/javascript"></script> 

but that's not working. Here's the error from the console:

crew.js:186 Uncaught TypeError: Cannot read property 'ldm' of null
at monthOnly (http://www.example.com/abc/public/js/crew.js:186:15)
at HTMLButtonElement.onclick     http://www.example.com/abc/public/crew.php:3021:112) 

I think the clue here is Cannot read property 'ldm' of null, it's not seeing the object. The file is being found when I check sources and network

You need to send a Javascript header at the very beginning of the PHP file to inform the page that the PHP script is outputting a JavaScript file.

Header("content-type: application/x-javascript");

Also the final output of the PHP script needs to be a valid .js file, whatever the PHP outputs must conform to valid JavaScript syntax.

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