简体   繁体   中英

Organising code that includes php and javascript files

I have a website where I am including a php library file and a javascript library file. I have condensed the problem to the following files:

index.php

<?php
  include('constants.php');
?>
<html>
  <head>
    <script type="text/javascript" src="lib.js"></script>
  </head>
  <body onload="javascript:show_const_1('<?php echo(CONST_TEXT); ?>');
                           show_const_2();">
    Some text here
  </body>
</html>

constants.php

<?php
  define('CONST_TEXT', 'Hello World');
?>

lib.js

function show_const_1(string)
{
  alert(string);
}

function show_const_2()
{
  alert('<?php echo(CONST_TEXT); ?>');
}

The result is that when the page loads I get two message boxes. The first says "Hello World" and the second says "<?php echo(CONST_TEXT); ?>". The first javascript method does what I want it to, but I will be using the function in many places across the site and so ideally I don't want to have to pass the constant as a parameter every time.

Is there a good way to rearrange the code to make the second javascript method work?

The simple answer is rename "lib.js" to "lib.php".

You should also add

header('Content-type: text/javascript');

to the top of the file.

Incidentally, you should us json_encode() to output text to javascript:

alert(<?php echo json_encode(CONST_TEXT); ?>);

And "javascript:" doesn't belong in event attributes (which are kindof outdated anyway):

<body onload="doSomething();">

alert()的方法主体不是由PHP解释的(它是由Javascript解释的),因此您不能在其中放入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