在Codeigniter中使用具有.php扩展名的外部js [英] Using external js with .php extension in Codeigniter
问题描述
我使用codeigniter 2,而且我的主题文件夹包含 js , img , css 文件夹。
I am using codeigniter 2 and I have my theme folder consist of js, img, css folders.
在 js 文件夹中,文件名为 js_functions.php 包含:
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; ?>
// ------------------------------------------------------------------------
,并调用查看档案
<script type="text/javascript" src="<?=base_url();?>themes/admin/js/js_functions.php"></script>
正确呈现。但它会在chrome的检查屏幕中返回:
renders correctly. But it returns in the chrome's inspect screen:
var base_url = '<br />
Uncaught SyntaxError: Unexpected token ILLEGAL
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 />
有什么问题?不是在外部js / php文件中使用php的正确方法吗?
What's wrong? Isn't it the correct way of using php in external js/php file?
推荐答案
剧本。可能 js
。在你的控制器中,您设置内容类型标题,并加载包含javascript以上的视图。假设你有一个控制器 js
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>
这篇关于在Codeigniter中使用具有.php扩展名的外部js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!