简体   繁体   中英

Move JavaScript with php code to external file

I wrote my script directly in my html file and works fine. 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.

I am using php in my JS like:

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

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

$scope.username = user_name;

Yes it is possible. I am using MVC framework on php.

I have a file called view_fncs.php which contains functions for header, navigation and footer eg:

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.

In my view.php file I do something like this:

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

You could set var $userName in the .php file. this way the variable $userName is assessable in the js file.

In php file:

<script>
    var $userName = <?php> echo $_SESSION['name'] ?>
</script>

<script src="js/someJs.js"></script>

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