2013-05-07 101 views
1

对于我网站上的每位用户,他们都有自己的资料页面和文章列表。当用户点击其中一个列表项目时,会发生动画,然后AJAX调用会显示一个显示文章的div。与此同时,我用一些JavaScript来强制URL变化来反映这一点:如何通过Codeigniter中的URL请求传递多个变量?

http://www.example.com/UserName/Hello-World-Article 

当用户点击浏览器中的后退按钮,它调用javascript函数动画回到列表视图状态。

到目前为止这么好。但让我们说,用户输入上面的URL到他们的地址栏并按下输入,这里是问题:

如何将'UserName'和'Hello-World-Article'变量传递到Codeigniter并正确使用它们这种情况下?

回答

9

对不起,我对你的问题的措辞有点困惑,但我想我明白你在谈论什么。

第一张:阅读Docs on Controllers。 Codeigniter文档的岩石。

第二个: URI的路由直接控制器类名称及其功能。

例如:

<?php 

    class Profile extends CI_Controller { 

     function item($username = NULL, $title = NULL) 
     { 
      if (is_null($username) || is_null($title)) redirect(base_url()); 

      // blah run code where $username and $title = URI segement 
     } 

    } 

这将产生此网址:

http://www.example.com/profile/item/username/whatever-i-want 

然后你可以在应用程序/配置/ routes.php文件使用路由删除项目(docs):

$route['(:any)'] = 'profile/item/$1'; 

虽然更好的方法(预读):

$route['profile/(:any)'] = 'profile/item/$1'; 

最后,这将创造你正在寻找的网址:

http://www.example.com/username/whatever-i-want 

//http://www.example.com/profile/username/whatever-i-want 

我可能需要仔细检查这个语法错误,但它的笨路由是如何工作的基本知识。一旦你的URL设置成这样,你就可以用JS来做任何你想做的事情。

然而,我强烈反对这种方法,因为路由一类像这样将几乎呈现应用程序/网站无用的其余部分,除非这是你唯一的控制器/功能(可能并非如此),你有。我认为只要在这种或那种URL中拥有一个类名就会更好。

或者,如果您想以非常规方式跳过路由,也可以像使用index()和$ this-> uri-> segment()一样使用。

<?php 

class Profile extends CI_Controller { 

    function index() 
    { 
     $username = $this->uri->segment(1); 
     $title = $this->uri->segement(2); 
    } 
} 

希望这是有道理的,并帮助您解决您的问题。

+0

谢谢!我正在使用替代方法。 – adrianmc 2013-05-11 12:29:17

+0

真的很好的答案! – 2015-07-23 14:12:16

0

怎么样只发送一个参数是分隔符分隔

url = http://www.example.com/UserName_title 

然后在你的控制器只是爆炸参数

class Profile extends CI_Controller { 

    function item($param = "") 
    { 
     if ($param == ""){ return false; } 

     $param = explode('_', $param); 
     $username = $param[0]; 
     $title = $param[1]; 
    } 
} 

有趣的部分是,您可以根据需要发送尽可能多的参数,而无需任何参数去技术。

PS:确保选择分隔符明智的,这样它不会在参数内容之一包括在内。