简体   繁体   中英

Script source file with php not parseing

I have a menu that appears on all my pages. It contains php for passing filenames to url's as follows. Here is a snippet...

document.write('<li><a href="somefile.php?folder=<?php echo "_abc"; ?>">abc</a></li>');
document.write('<li><a href="somefile.php?folder=<?php echo "_def"; ?>">def</a></li>');
document.write('<li><a href="somefile.php?folder=<?php echo "_ghi"; ?>">ghi</a></li>');

It includes css and that works fine. I have saved the menu as a seperate .js file and used...

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

...to load it from each page that I want it to appear. The menu displays and the css works fine - however the php does not parse and the page shows the php markup. What am I doing wrong?

Thanks in advance. Neil

You shouldn't do it like that.

Have a page called menu.php saved somewhere, which includes:

<ul>

    <li><a href="somefile.php?folder=<?php echo "_abc"; ?>">abc</a></li>
    <li><a href="somefile.php?folder=<?php echo "_def"; ?>">def</a></li>
    <li><a href="somefile.php?folder=<?php echo "_ghi"; ?>">ghi</a></li>

</ul>

Then include it, on the server side (index.php):

<html>
<head>
    <title></title>
</head>
<body>
<header>
    <?php include("main.php"); ?>
</header>
</body>
</html>

This approach is far superior:

  • It does not require an extra request to get the data.
  • There will be no flickering or awkward moments of data loading, the menu would appear as if you've coded it directly into the page.
  • It's much faster.
  • It doesn't use JavaScript, which the client can choose to disable.

You confuse server side and client side. PHP is about server side and PHP code it is interpreted on server. JavaScript is about client side, and JavaScript runs when user already has gotten html page, so when you dinamically add php in html on client side by JavaScript it cannot be run.

From what I understood I think that you are Trying to run PHP inside a .js file.
You should include that code in a PHP file.

The problem you're experiencing is probably due to the fact that you're attempting to run PHP on a .js file, and your server is not configured to it.

Change the file's extension to .php and use:

<script src="js/menucss.php">

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