duan36000 2012-04-11 15:00
浏览 32
已采纳

在Codeigniter中使用带有.php扩展名的外部js [关闭]

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?

  • 写回答

3条回答 默认 最新

  • dqeq885710 2012-04-11 17:17
    关注

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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?