在PHP页面中包含许多javascript函数(使用PHP)的最有效方法是什么?

问题描述:

In one of my sites, I need to use PHP 'foreach' to keep including some Javascript code. In this code contains PHP $variables that change within the foreach loop.

foreach ($a as $b) {
   include("javascript.php");  
}

javascript.php contains codes like this:

<script>
   $(".<?php echo $somevariable?>").something;
</script>

My question is: What is the most efficient (if any) way to load javascript that contains PHP variables?

I keep reading that it's better to call large javascript codes in a .js script rather than writing it on the page, But apparently .js files can not have PHP.

Thanks for your insight.

在我的一个网站中,我需要使用PHP“foreach”来保留包含一些Javascript代码。 在此代码中包含在foreach循环中更改的PHP $变量。 p>

  foreach($ a as $ b){
 include(“javascript.php”);  
} 
  code>  pre> 
 
 

javascript.php包含以下代码: p>

 &lt; script&gt; 
 $(  “。&lt;?php echo $ somevariable?&gt;”)。某事; 
&lt; / script&gt; 
  code>  pre> 
 
 

我的问题是:什么是效率最高的( 如果有的话)加载包含PHP变量的javascript的方法吗? p>

我一直在读,最好在.js脚本中调用大的javascript代码而不是在页面上编写它,但显然。 js文件不能有PHP。 p>

感谢您的见解。 p> div>

Here is the approach I would use:

Create your HTML file with a Javascript variable containing $somevariable:

<html>
<head>
    <script src="my_global.js"></script>
</head>
<body>
    Foo
<script>
    var somevariable = "<?php echo $somevariable ?>";
</script>
</body>
</html>

Then have the Javascript file access this value once the page is ready (I'm using jQuery .ready() in this example):

$(document).ready(function() {
    alert(somevariable);
});

Here it is in action: http://jsfiddle.net/2zeQM/

This allows the Javascript file to be cached (it's static and not dynamic). And the dynamic data is loaded on the page being requested by the user.

You do need to be careful that the variable name you use does not get reused by any other Javascript code. To prevent problems, I would prefix the variable name. For example, instead of calling it "somevariable", I might call it "xy_somevariable"

you can add:

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

to the top of your .php file and it will render as a .js file.