I need my server to send JS file but I need it to be actually a PHP generated file.
I am using Apache with PHP.
So that function named
doSomething(){
};
can be
doSomething(){
<?php
if(registeredUser()){
echo "Doing something!";
}
?>
};
Give the file a php extension but load it like normal JavaScript
<script type="text/javascript" src="/javascript.php"></script>
Send the proper content-type in your PHP file:
header("content-type: text/javascript");
This allows your server to create JavaScript with PHP.
You don't need to do any magic. The browser doesn't care what created the Javascript, so long as the Javascript is valid!
That said, you should send the correct Content-type
header:
header('Content-type: text/javascript');
You can do this by simply using a PHP file as your script's src
attribute:
<script src="myfile.php"></script>
However, having another PHP script run is not ideal from a resources point of view. Another PHP process is triggered, you have to take care of caching, etc.
Consider whether you can't have static code in your JS file, and set the condition you're checking for in your main file, where you have PHP running anyway.
In the JavaScript file (myfile.js):
function doSomething()
{ if (logged_in) do_something() }
In the main file's <head>
, do:
<script>
<?php if (registeredUser()): ?>
logged_in = true;
<?endif; ?>
<script>
and then include the static JS file as usual.
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.