基于城市的控制器功能在网址CodeIgniter中

时间:2015-07-30 05:15:34

标签: php codeigniter url-routing

我正在使用CodeIgniter中的网站。

我希望我的网站用户从下拉列表中选择城市,然后根据该城市显示内容。为此我有两个问题。

1)如何向URL段添加新参数。我查了this。创建城市作为控制器是否可以?但那我应该如何创建当前的控制器?如果是的话,

2)问题是我已经在所有控制器上工作了。

指导我如何继续。

2 个答案:

答案 0 :(得分:1)

您可以将uri段作为参数传递给控制器​​。

http://YOUR_URL.com/index.php/city/get/zurich

<?php
class City extends CI_Controller {

        public function get($city)
        {
                echo $city;
        }
}

http://www.codeigniter.com/user_guide/general/controllers.html#passing-uri-segments-to-your-methods

修改

只是为了给你一个想法:

首先从URL中删除index.php:

创建.htaccess文件

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# When CI is in a subfolder use this line instead
#RewriteRule ^(.*)$ /ci/index.php/$1 [L,QSA]
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

打开文件/application/config/config.php并搜索

$config['index_page'] = 'index.php';

并将其更改为

$config['index_page'] = '';

打开文件/application/config/routes.php并将此行添加到其他规则

$route['(:any)/(:any)/(:any)'] = "$2/$3/$1";

控制器看起来像这样。

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class City extends CI_Controller {

    public function index($city)
    {
        echo $city;
    }
}

所以我只是改变了细分的顺序。 2 = Class,3 = Method,1 = parameters。

答案 1 :(得分:0)

试试这个。 - 首先告诉我你从下拉列表中选择一个城市后如何发送请求。 -anyways我会告诉你,首先将jquery'change'事件添加到下拉列表中,并且在更改时你必须将下拉列表的当前值添加为 例如

$('#idOfDropDownlist').on('change',function(){
    var value = $(this).val();
    //now send a ajax request to controller to get information about city.
    $.ajax({
    type:'get',
    url:"<?php echo base_url(); ?>ControllerName/methodName/"+value,
    success:function(response){
     console.log(response);
}
});
});

//---- your controller's method for getting this request will be like.

class ControllerName .....{
public function methodName($city = ''){
//--- here you got the city name,so do whatever u want with......
}
}