2013-12-16 43 views
3

我以CI開始,我需要一些幫助。我試圖用Ajax加載一些html頁面,這個html文件存儲在視圖文件夾中,我試圖使用控制器訪問這些文件,直到現在我還沒有成功。我想知道,我如何訪問這些文件,並且如果我使用的控制器是正確的,或者有更好的方法來完成此操作。CodeIgniter中的鏈接,控制器

控制器

class Router extends CI_Controller 
{ 
    public function index($file) 
    { 
      $this->load->view($file); 
    } 
} 

阿賈克斯

var SampleFunction = function (router) {//router is my base_url() + '/router' 
    var pageContentBody = $('.page-content .page-content-body'); 

    if ($("#startLoadTag")){ 
     $.ajax({ 
      type: "post", 
      cache: false, 
      url: router + '/SampleLink.html', 
      dataType: "html", 
      success: function (html) { 
       pageContentBody.html(html); 
      } 
     }); 
    } 
} 

到現在爲止我只得到404未找到。

+0

不知道你是否有有apache配置爲刪除索引,但如果不是,你應該擊中路由器+'/index/SampleLink.html' – Rooster

+1

無法將參數傳遞給codeigniter中的'function index()'。將''作爲方法路由。最簡單的就是創建另一個函數並在你的ajax路徑中使用它 – charlietfl

+0

好的,我修復了這些bug。但是現在我對系統有一個很大的安全漏洞。如果我在Chrome上更改HTML鏈接名稱並單擊鏈接,則會加載該文件。有任何阻止更改鏈接名稱或東西來增加安全性。你的建議是什麼? – user3108967

回答

1

您的首要問題在於您的索引函數僅在URI爲/router/時纔會被調用。最簡單的解決方案是命名你的方法是不同的:

class Router extends CI_Controller { 
    public function details($file) { 
      $this->load->view($file); 
    } 
} 

的URI的SampleLink.html現在會是什麼樣子:/router/details/SampleLink.html。這很簡單,應該沒有任何問題。此外,它不應該干擾該控制器中的任何其他方法。

如果你真的不喜歡更長的URL,那麼你可以通過實施_remap()方法來縮短它。但是,如果你這樣做,請記住你重寫了控制器的所有默認方法映射行爲。

通過此實施,您可以使用URI /router/SampleLink.html。但這就是你所能做的。控制器中沒有其他方法可以訪問。

class Router extends CI_Controller { 
    public function _remap($file) { 
      $this->load->view($file); 
    } 
} 

最後,如果你想使用的文件的自定義映射關係,但保留控制器的常用函數映射的行爲,你可以做這樣的事情:

class Router extends CI_Controller { 

    public function _remap($method, $args=array()) { 

      $callable = array($this, $method); 

      if ($method[0] != '_' && is_callable($callable)) 
       // If $callable really is a usable method in this class, then 
       // go ahead and invoke it with the given $args array. Make sure 
       // to exclude method names starting with '_', which are supposed to 
       // be kept private and inaccessible from the web. 
       call_user_func_array($callable, $args); 
      else 
       // Otherwise, look for a view with the name $method. Hopefully, 
       // this will be something like "SampleLink.html", which exists in 
       // the views folder. 
       $this->load->view($method); 
    } 

} 
+0

Tks!這隻對我有用。 – user3108967