在.js文件中执行PHP代码 [英] Executing PHP code inside a .js file
问题描述
我试图在.js文件中执行一些PHP,但是显然不知道如何正确执行.
I'm trying to get a bit of PHP to execute inside of a .js file, but obviously don't know how to do it properly.
基本上,代码是在页面上添加了一些HTML标记,我将这些标记用于滑出式联系表单.但是,联系表本身是在Wordpress中通过短代码完成的.因此,我试图使短代码能够在使表格滑出的代码内运行.
Basically the code is adding some HTML tags to my page, which I am using for a slideout contact form. However the contact form itself is done in Wordpress by a shortcode. So I'm trying to get the shortcode to work inside the code that makes the form slide out.
var phpTest = '<?php do_shortcode("[contact-form-7 id=\'1088\' title=\'Live Chat Form\']"); ?>';
// add feedback box
$this.html('<div id="fpi_feedback"><div id="fpi_title" class="rotate"><h2>'
+ thisSettings.title
+ '</h2></div><div id="fpi_content">'
+ phpTest
+ '</div></div>');
如果我将变量"phpTest"更改为带有文本的常规字符串,则显示效果很好,我只是不确定在这种情况下如何执行php.
If I change the variable "phpTest" to a regular string with text, it shows up fine, I'm just not sure how to execute the php in this instance.
推荐答案
编辑:脚本类型应始终为text/javascript
,因为application/javascript
可能会破坏与旧版浏览器的兼容性(我认为IE8和之前的版本将忽略该类型的脚本标签).但是,内容类型仍应为application/javascript
.
EDIT: The script type should always be text/javascript
as application/javascript
may break compatibility with older browsers (I think IE8 and earlier will ignore the script tag with that type). The Content-type, however, should still be application/javascript
.
您不能像普通的.php
文件那样将php混入.js
文件中,因为.js
文件没有像.php
那样由.php
引擎预处理文件.
You can't mix in php into a .js
file, the way you would with a normal .php
file, since the .js
file is not preprocessed by the .php
engine the way your .php
files are.
最典型的方法(包括js文件中的php)是在.php文件中仅包含内联JS(在<script>
标记之间的内容).然后它将按预期工作.
The most typical way to do this--including php in a js file--is to just have inline JS (stuff between <script>
tags) in your .php file. Then it will work as expected.
另一种可行的方法是在php中创建一个js文件,因此请使用以下方式启动您的.php文件
Another way to go is to make a js file within php, so start your .php file with
<?php
header("Content-type: application/javascript");
?>
var jsvar='something';
var othervar='<?php echo $phpVar; ?>';
//<?php //some php ;?>
然后像这样将其包含在您的页面中
and then include it on your page like this
<script src='myjs.php' type='text/javascript'></script>
这篇关于在.js文件中执行PHP代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!