Using external js with .php extension in Codeignit

2019-03-22 05:36发布

问题:

I am using codeigniter 2 and I have my theme folder consist of js, img, css folders.

Inside js folder, file name is js_functions.php contains:

<?php header("Content-type: text/javascript"); ?>
/**
 * GLOBAL VARIABLES & PATHS
 *
 * path definitions for jquery inline usage
 *
 */     
var base_url         = '<?=base_url();?>';
// ------------------------------------------------------------------------

/**
 * jquery.message Global Implementation
 *
 * Shows message if any session flashdata named message is set
 *
 */

<?php if($this->session->flashdata('message')):?>
$(function() { $().message("<?=$this->session->flashdata('message');?>"); });
<?php endif; ?>

// ------------------------------------------------------------------------

and, calling in it view file

<script type="text/javascript" src="<?=base_url();?>themes/admin/js/js_functions.php"></script>

renders correctly. But it returns in the chrome's inspect screen:

var base_url         = '<br />
Uncaught SyntaxError: Unexpected token ILLEGAL

and in the browser when you call the page from address bar:

var base_url         = '<br />
<b>Fatal error</b>:  Call to undefined function base_url() in <b>F:\xampp\htdocs\themes\js\js_functions.php</b> on line <b>11</b><br />

What's wrong? Isn't it the correct way of using php in external js/php file?

回答1:

You need to make a controller to get the script. May be js. Inside your controller you set the content type headers and load the view which contains above javascript. Lets say you have a controller called js

class Js extends CI_Controller{
  public function js_functions(){
    $this->output->set_header('Content-type: text/javascript');
    $data = array( 'messages' => $this->session->flashdata('message'));
    $this->load->view('jsfunc',$data);
  }
}

And you can load the script in the main view like this

<script src="<?php echo base_url('js/js_functions'); ?>"></script>


回答2:

If you want to generate dynamic js, css files. Use standart MVC method. Make a folder in view folder with name js or css. Create js or css files as php view file. For example : slider.js.php.

Make a controller themejs.php. Forward all js or css files to this controller which you need, by using routing. And inside this controller make dynamic action, pass varibles to js, css view files. And print them with header



回答3:

base_url() is a function part of the CI url helper. If you want to make use of it in that file and you don't want to create an instance of the $CI object, you will have to implement your own version of that function.