在外部 Javascript 文件中使用 PHP 代码 [英] Use PHP code in external Javascript file

查看:31
本文介绍了在外部 Javascript 文件中使用 PHP 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道是否可以使用包含 PHP 代码的外部 JS 文件.

I am just wondering if it's possible to use external JS file that contains PHP code.

我的外部JS

$(document).ready(function(){

    $('#update').click(function(){
    var tableVal={};
    // a bit of php code I need in JS
    var search_city=<?php echo $_SESSION['search_city'];?>';
$.post('<?=base_url()?>/project_detail/pub', {'tableVal':tableVal},function(message)

        })
    })
})

我的查看页面

<script type="text/javascript" src="<?= base_url();?>js/external.js"></script>

JS 不起作用,因为我认为 JS 中的 PHP 代码是问题所在.有什么想法吗?非常感谢.

The JS doesn't work as I assume that the PHP code in JS is the problem. Any thoughts? Thanks a lot.

推荐答案

您可以通过将 js 文件重命名为 php 并在 中使用此链接来实现>script 标签 src (如其他答案中所指出的)

You can do it by either renaming you js file to php and using this link in script tag src (as pointed in other answers)

虽然这似乎是一种很好且简单的方法,但有很多理由不这样做.

While this may seems a good and easy way there is many reason not to do this.

  • 缓存(您生成的脚本不会被缓存,这可能会改变但需要额外的工作)
  • 内存消耗(对这个生成的 js 文件的每个请求都需要 php)
  • Caching (your generated script will not be cached, this may be changed but require additional work)
  • Memory consumption (every request to this generated js file will require php)

您可以简单地更改为这样的东西来完成它(以更好的方式,IMO):

You can simply changed to something like this to get it done (in a better way, IMO):

<script type="text/javascript">
  var Settings = {
    base_url: '<?= base_url() ?>',
    search_city: '<?= $_SESSION['search_city'] ?>'
  }
</script>
<script type="text/javascript" src="<?= base_url();?>js/external.js"></script>

你的 js 的内容变成了这样:

Than content of your js became something like this:

$(document).ready(function(){
  // I assume that not using search_city in your sample code
  // and some syntax errors, is just by mistake...
  $('#update').click(function(){
  var tableVal={search_city:Settings.search_city};
  $.post(Settings.base_url+'/project_detail/pub',
    {'tableVal':tableVal},
    function(message){
      console.log(message);
    })
  })
})

这篇关于在外部 Javascript 文件中使用 PHP 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆