這是目前 2.1.4 版,Javascript Class 的官方教學文件
http://www.codeigniter.org.tw/user_guide/libraries/javascript.html
注意:網址沒有標明版本,所以內容可能自動隨著版本不同而變。
照做之後,會出現 Undefined variable $library_src and $script_head 或是 Unable to load the requested class: jquery 的錯誤訊息。
國外論壇 stackoverflow 這篇有人發問。還有這篇 。整理之後如下。
在 application/config/config.php 這支檔案,新增一個變數:
$config['javascript_location'] = 'http://localhost/codeigniter/application/libraries/js/jquery-1.11.0.min.js';或是
$config['javascript_location'] = APPPATH.'libraries/js/jquery-1.11.0.min.js';
在 application/controllers 裡面的檔案,以教學文件之前的範例 news.php 為例
在它的 public function __construct() 這個函數裡面,要新增 $this->load->library('javascript');
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
$this->load->library('javascript');
}
在 public function index() 這個函數裡面,要新增 $data['library_src'] = $this->jquery->script(); 及 $data['script_foot'] = $this->jquery->_compile();
public function index()
{
$data['library_src'] = $this->jquery->script();
$data['script_foot'] = $this->jquery->_compile();
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}
然後在 views/templates/header.php ,新增 $library_src 及 $script_foot
<html>
<head>
<title><?php echo $title ?> - CodeIgniter 2 教學</title>
<?php echo $library_src;?>
<?php echo $script_foot;?>
<script>
$(document).ready(function() {
alert ('Hello World');
});
</script>
</head>
<body>
<h1>CodeIgniter 2 教學</h1>
如果 jquery 是放在本機上:application/.htaccess 原本只有 Deny from all,要新增 Allow from 127.0.0.0/24。 如果直接使用 jquery 網站的檔案,例如 http://code.jquery.com/jquery-1.11.0.min.js,.htaccess 就不用改。
然後執行 http://localhost/codeigniter/news ,就可以看到 alert ('Hello World'); 的效果。
官方手冊的問題:
- $config['javascript_location'] 要指定到檔案,而不是資料夾。
- 這行不用寫:$this->load->library('jquery'); 。雖然手冊前面說 jquery 會隨著 $this->load->library('javascript'); 自動載入,但是後面又說,如果要手動載入,可以加jquery 那一行。但問題是,這兩行如果同時存在會有問題,只有 $this->load->library('jquery'); 也有問題。所以只要載入 $this->load->library('javascript'); 這個就好了。
- header.php 裡面,手冊的變數是 $script_head,要改成 $script_foot
但是這樣做的話,每個方法都要設定 $data['library_src'] 跟 $data['script_foot'] 。直接在 header.php 把 jquery 檔載入就好了,幹嘛這麼麻煩?大概用意是,在需要變更調整的時候,可以選擇要不要載入 jquery,或是載入不同的 jquery。
我應該還是會直接把連結寫在 header.php 吧,比較省事。
沒有留言:
張貼留言