Running Javascript in PHP
I'm loading an external .php file using:
<script type="text/javascript" src="myfile.js.php"></script>
Within the开发者_运维知识库 external myfile.js.php file, I'm using:
<?php
header('content-type: text/javascript');
$message = "Test message";
?>
document.write('<?php echo $message; ?>');
Everything works fine until I change the name of myfile.js.php to just myfile.php
Why does it stop working if I remove the .js part from the file name? I'm serving the file as text/javascript, plus shouldn't the .js part be ignored since .php is the actual file extension?
In both cases, the file extension is php, "myfile.js.php" and "myfile.php" - both file extensions are "php", so that isn't the problem.
Are you definitely changing the physical file name and the src attribute - or are you just changing the physical file name and forgetting to change the script tag to...
<script type="text/javascript" src="myfile.php"></script>
UPDATE: Having Seen The File In Action...
If you look inside of myfile.php, it has a little extra appended to the script, so it starts off well...
document.write('Test message');
But then there is a script block inside of the script file - which is being added to all files...
<!-- Analytics Code -->
<script type="text/javascript" src="http://..."></script>
<noscript>....</noscript>
It is this analytics code that causes the syntax error as these cannot be parsed by the JavaScript engine.
it works fine for me (in firefox and ie) :S.. please check this:
- try displaying the myfile.php in a separate window
- Is the file been parsed as a php file?
- check the headers of the server response to see if the content-type is being sent correctly
Good luck
Unfortunately I was unable to reproduce your problem and maybe this is not the answer, but I would suggest checking Apache configuration file httpd.conf. For example. search it for instances of ".js". Also, there is a file named mime.types that associates MIME-TYPE with file extensions. Perhaps there are some errors?
Hope that will help you somehow.
精彩评论