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

查看:93
本文介绍了在外部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 并在脚本标记 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 的内容这个:

$(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天全站免登陆