Include PHP inside JavaScript (.js) files
I have a JavaScript file (extension .js
, not .html
) containing several JavaScript functions.
I want to call one of the PHP functions in a PHP file containing only several PHP functions from within one of the JavaScript functions.
.php
file containing the PHP function in the .js
file? For example, say I had a file called myLib.php containing a function called
myFunc
that takes two parameters ( param1
and param2
). Then I have a .js
file containing a function called myJsFunc
. How would a call the myFunc
(PHP) from within the myJsFunc
(JavaScript function)? Wouldn't I need to include the PHP file somehow in the .js
file? 7 years later update: This is terrible advice. Please don't do this.
If you just need to pass variables from PHP to the javascript, you can have a tag in the php/html file using the javascript to begin with.
<script type="text/javascript">
phpVars = new Array();
<?php foreach($vars as $var) {
echo 'phpVars.push("' . $var . '");';
};
?>
</script>
<script type="text/javascript" src="yourScriptThatUsesPHPVars.js"></script>
If you're trying to call functions, then you can do this like this
<script type="text/javascript" src="YourFunctions.js"></script>
<script type="text/javascript">
functionOne(<?php echo implode(', ', $arrayWithVars); ?>);
functionTwo(<?php echo $moreVars; ?>, <?php echo $evenMoreVars; ?>);
</script>
AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js
<FilesMatch ".(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>
Add the above code in .htaccess file and run php inside js files
DANGER: This will allow the client to potentially see the contents of your PHP files. Do not use this approach if your PHP contains any sensitive information (which it typically does).
If you MUST use PHP to generate your JavaScript files, then please use pure PHP to generate the entire JS file. You can do this by using a normal .PHP file in exactly the same way you would normally output html, the difference is setting the correct header using PHP's header function, so that the correct mime type is returned to the browser. The mime type for JS is typically " application/javascript "
A slightly modified version based on Blorgbeard one, for easily referenceable associative php arrays to javascript object literals:
PHP File (*.php)
First define an array with the values to be used into javascript files:
<?php
$phpToJsVars = [
'value1' => 'foo1',
'value2' => 'foo2'
];
?>
Now write the php array values into a javascript object literal:
<script type="text/javascript">
var phpVars = {
<?php
foreach ($phpToJsVars as $key => $value) {
echo ' ' . $key . ': ' . '"' . $value . '",' . "n";
}
?>
};
</script>
Javascript file (*.js)
Now we can access the javscript object literal from any other .js file with the notation:
phpVars["value1"]
phpVars["value2"]
链接地址: http://www.djcxy.com/p/42498.html