[英]How to send a JS file from my server when it actually is a php?
I need my server to send JS file but I need it to be actually a PHP generated file. 我需要服务器发送JS文件,但实际上需要它是PHP生成的文件。
I am using Apache with PHP. 我正在将Apache与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 给文件一个php扩展名,但像普通JavaScript一样加载它
<script type="text/javascript" src="/javascript.php"></script>
Send the proper content-type in your PHP file: 在您的PHP文件中发送正确的内容类型:
header("content-type: text/javascript");
This allows your server to create JavaScript with PHP. 这使您的服务器可以使用PHP创建JavaScript。
You don't need to do any magic. 您不需要做任何魔术。 The browser doesn't care what created the Javascript, so long as the Javascript is valid! 只要Javascript有效,浏览器就不在乎创建Javascript的原因!
That said, you should send the correct Content-type
header: 也就是说,您应该发送正确的Content-type
标头:
header('Content-type: text/javascript');
You can do this by simply using a PHP file as your script's src
attribute: 您可以通过简单地使用PHP文件作为脚本的src
属性来执行此操作:
<script src="myfile.php"></script>
However, having another PHP script run is not ideal from a resources point of view. 但是,从资源角度来看,运行另一个PHP脚本并不理想。 Another PHP process is triggered, you have to take care of caching, etc. 触发了另一个PHP进程,您必须注意缓存等问题。
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. 考虑一下您的JS文件中是否不能包含静态代码,并在要运行PHP的主文件中设置要检查的条件。
In the JavaScript file (myfile.js): 在JavaScript文件(myfile.js)中:
function doSomething()
{ if (logged_in) do_something() }
In the main file's <head>
, do: 在主文件的<head>
,执行以下操作:
<script>
<?php if (registeredUser()): ?>
logged_in = true;
<?endif; ?>
<script>
and then include the static JS file as usual. 然后照常添加静态JS文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.