Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

jquery - Use PHP code in external Javascript file

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

my external 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)

        })
    })
})

my view page

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

  • 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)

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>

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);
    })
  })
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...