我理解好的做法是将.js文件添加到HTML
的头部。
我的问题是,我的一个.js文件(或code+script)也有一个beginning
函数,它看起来像这样(所有这些现在都在头上):
<?php
// Countdown timer
function timer($date, $id){ ?>
<script>
(function()
{
// random stuff
}
</script>
// end function timer
<?php } ?>
我应该如何在我的<script> src=" x "</script>
中包含/要求或HTML
这类文件?由于beginning
函数,我很难弄清楚如何以正确的方式添加这个文件。
发布于 2016-05-25 20:58:34
首先,将其替换为:
<script> src=" x "</script>
在这方面:
<script src=" x "></script>
现在,如果我正确理解它,您希望将一个.php文件包含到页面的header中,并且这个.php文件应该包含一个js脚本。
类似于:
index.html
<head>
<title>My Weird App</title>
<?php include "myphpfile.php" ?>
</head>
myphpfile.php
<?php
some_func() { ?>
<script src="myjsfile.js"></script>
<?php } ?>
myjsfile.js
function some_other_function() {
//do stuff
}
如果您想在调用php函数时执行一些javascript代码。这是可以的,但是如果您希望能够在javascript上使用从php返回的值,或者相反,那么它就不会像您预期的那样工作。客户机/服务器通信的首选方法是AJAX。
如果希望基于条件包含.js文件,则通过以下方法可以做得更好:
myphpfile.php
<?php
some_func(some_params) {
if(some_cond) {
return "<script src="myjsfile.php"></script>\n"
} else {
return "";
}
}
?>
然后在index.html上
<head>
<title>My not so weird app</title>
<?php
include 'myphpfile.php';
echo some_func(some_arguments);
?>
</head>
好吧,我希望这有帮助,如果我不明白,请评论,(或者让你的问题更清楚)。
https://stackoverflow.com/questions/37450853
复制相似问题