简体   繁体   中英

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'.

How should I return it from 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:

<?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

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