[英]Move JavaScript with php code to external file
I wrote my script directly in my html file and works fine. 我直接在html文件中编写了脚本,并且工作正常。 I want to move my script to external file, of course I know how to move it to external file for example js/myscript.js then add it in my html but I am also using php
and there is a problem because it isn't working when it's in external file. 我想将脚本移动到外部文件,当然我知道如何将其移动到外部文件,例如js / myscript.js,然后将其添加到我的html中,但我也在使用php
,这是一个问题,因为它不是在外部文件中时工作。
I am using php in my JS like: 我在我的JS中使用php,例如:
user_name = "<?php echo $_SESSION['name'] ?>";
$scope.username = user_name;
and this is where I am starting session 这是我开始会议的地方
<?php session_start();
if(!isset($_SESSION[ 'username'])) {
header( "Location: login/login.php");
}
?>
<!DOCTYPE html>
How can I use it in external file? 如何在外部文件中使用它? is it possible? 可能吗?
May use a JS variable in main html page for user_name
and this variable can be used in external JS 可以在html主页面中将JS变量用作user_name
并且该变量可以在外部JS中使用
<?php session_start();
if(!isset($_SESSION[ 'username'])) {
header( "Location: login/login.php");
}
?>
<!DOCTYPE html>
<head>
<script>
var user_name = "<?php echo $_SESSION['name'] ?>";
</script>
<script src="js/yourexternal.js"></script>
</head>
in yourexternal.js 在yourexternal.js中
$scope.username = user_name;
Yes it is possible. 对的,这是可能的。 I am using MVC framework on php. 我在php上使用MVC框架。
I have a file called view_fncs.php which contains functions for header, navigation and footer eg: 我有一个名为view_fncs.php的文件,其中包含用于页眉,导航和页脚的函数,例如:
function showHeader($title="My Title")
{
echo '<!DOCTYPE HTML>';
echo '<html lang="en">';
echo '<head>';
echo '<title>' .$title. '</title>';
echo '<meta http-equiv="content-type" content="text/html;charset=utf-8" />';
echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
echo '<script src="js/javascript.js" type="text/javascript"></script>';
echo '</head>';
echo '<body>';
}
As you can see it has a link to the JS file. 如您所见,它具有指向JS文件的链接。
In my view.php file I do something like this: 在我的view.php文件中,我做这样的事情:
<?php
include ("view_fncs.php");
showHeader("Add a new submission");
?>
The same principal applies to other script. 相同的主体适用于其他脚本。 Just link the two files with include
and then specify the function. 只需将两个文件与include
链接,然后指定功能即可。
You could set var $userName in the .php file. 您可以在.php文件中设置var $ userName。 this way the variable $userName is assessable in the js file. 这样,变量$ userName可在js文件中评估。
In php file: 在php文件中:
<script>
var $userName = <?php> echo $_SESSION['name'] ?>
</script>
<script src="js/someJs.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.