简体   繁体   English

从PHP返回JS源代码

[英]Return JS source code from PHP

On website I have embedded some Script 我在网站上嵌入了一些脚本

<script src="somesite.com/getCode.php"></script>

And when the request is made I want to return JavaScript code from 'getCode.php'. 当发出请求时,我想从“ getCode.php”返回JavaScript代码。

How should I return it from PHP? 我应该如何从PHP返回它?

Well, you have to do something like this: 好吧,您必须执行以下操作:

<script type='text/javascript'>
   <?php echo file_get_contents("somesite.com/getCode.php"); ?>
</script>

Make sure the path to the file is correct. 确保文件路径正确。

You just need to output the correct header for js, then output the js: 您只需要为js输出正确的标头,然后输出js:

<?php
$somevar = 'hello from php via js';
header('Content-Type: application/javascript');
?>
alert('<?php echo $somevar;?>');
<?php
// Filename: getCode.php
header("content-type: application/javascript");
echo 'function foo(){ console.log("Foo is running"); }';
die();

or 要么

<?php
// Filename: getCode.php
header("content-type: application/javascript");
?>
// your js code in plain text
function foo(){ console.log("Foo is running"); }

For understanding media-type (aka content-type) you should read this RFC at section 7 http://www.rfc-editor.org/rfc/rfc4329.txt 为了了解媒体类型(又称内容类型),您应该在第7节http://www.rfc-editor.org/rfc/rfc4329.txt上阅读此RFC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM