dongpan1416 2012-04-12 03:46
浏览 33
已采纳

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

  • 写回答

2条回答 默认 最新

  • dongmiyi8220 2012-04-12 05:30
    关注

    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"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看