歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> PHP CI框架學習之路徑訪問

PHP CI框架學習之路徑訪問

日期:2017/3/1 10:29:15   编辑:Linux編程

CI是一個PHP寫的框架,使用它寫網站非常方便,但是也會也有一些糾結的問題,比如說其中文件的路徑訪問。

CI嚴格貫徹MVC思想,因此基於此思想的文件訪問也比較嚴格,controllers控制器是所有view的入口,從URL上是不能直接訪問view的,必須通過控制器,也就是說要寫控制器的路徑,在寫代碼的時候,路徑也是不能隨便寫的。

一般CSS、JS、圖片文件我們會放到items下,比如說我們想在PHP文件中訪問某個圖片文件calendar-hilite.gif如下圖所示:


就可以這樣寫圖片的路徑base_url("items/image/calendar/calendar-hilite.gif")。其中,base_url代表http://localhost/網站名/,而items下的文件,在URL中是可以直接訪問的。其實localhost代表的位置是可以在控制文件中設置的,只是一個代表。

而有時我們所要的文件並不一定要寫到items下,我們也可能要寫到view下,或者控制器下,這是就有兩種方式:一個是使用base_url,另一個是使用"./"或者"../"這種通用的路徑訪問形式,舉個例子,比如說我要寫一個用Ajax實現的某個功能,其代碼如下:

[javascript]
  1. $.ajax({
  2. type:"POST",
  3. url:"<?php echo site_url("ajax_part/getCommentDetail");?>",
  4. data:{
  5. product_id :id,
  6. comment_first_id:first,
  7. comment_last_id:last
  8. } ,
  9. success:function(data)
  10. {
  11. $("#"+id).empty();
  12. $("#"+id).html(data);
  13. }
  14. });
其中url是我要訪問的服務器文件位置,由於我吧這個文件,叫做ajax_part.php放在了控制器下,那麼我訪問的時候就有一些困難。但是用site_url就比較好辦,site_url就代表http://localhost/網站名/index.php這樣就可以通過URL的形式訪問控制器文件,另一種方式是這樣寫:

[javascript]
  1. $.ajax({
  2. type:"POST",
  3. url:"../ajax_part/getCommentDetail",
  4. data:{
  5. product_id :id,
  6. comment_first_id:first,
  7. comment_last_id:last
  8. } ,
  9. success:function(data)
  10. {
  11. $("#"+id).empty();
  12. $("#"+id).html(data);
  13. }
  14. });
因為我當前的VIew頁面是這樣的形式:http://localhost/EShop/index.php/index2/index,那麼我就用..退回到EShop(“是我的網站名”)下,再訪問ajax_part/getCommentDetail就可以了。

這就是基本的思路,可能不需要說的這麼復雜。

ajax_part.php的大致代碼如下:

[php]
  1. <?php
  2. class Ajax_part extends CI_Controller {
  3. function __construct() {
  4. parent::__construct ();
  5. //something
  6. }
  7. function getCommentDetail() {
  8. //something
  9. }
  10. }
  11. ?>
Copyright © Linux教程網 All Rights Reserved