简体   繁体   English

整理包含php和javascript文件的代码

[英]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. 我有一个网站,其中包含一个php库文件和一个javascript库文件。 I have condensed the problem to the following files: 我已将问题压缩为以下文件:

index.php 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 constants.php

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

lib.js 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); ?>". 第一个说“ Hello World”,第二个说“ <?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. 第一个javascript方法可以实现我想要的功能,但是我将在网站的许多地方使用该函数,因此理想情况下,我不想每次都将常量作为参数传递。

Is there a good way to rearrange the code to make the second javascript method work? 有没有一种好的方法来重新排列代码以使第二个javascript方法正常工作?

The simple answer is rename "lib.js" to "lib.php". 简单的答案是将“ lib.js”重命名为“ 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: 顺便说一句,您应该使用json_encode()将文本输出到javascript:

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

And "javascript:" doesn't belong in event attributes (which are kindof outdated anyway): 而且“ javascript:”不属于事件属性(无论如何,它们都是过时的):

<body onload="doSomething();">

alert()的方法主体不是由PHP解释的(它是由Javascript解释的),因此您不能在其中放入PHP标记

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM