【问题标题】:City based controller function in url CodeIgniterurl CodeIgniter 中基于城市的控制器功能
【发布时间】:2015-08-01 18:03:30
【问题描述】:

我正在使用 CodeIgniter 开发一个网站。

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

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

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

指导我应该如何进行。

【问题讨论】:

  • 您可以创建单个控制器并将下拉列表中发布的国家名称作为控制器功能参数传递。

标签: php codeigniter url-routing


【解决方案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 = 类,3 = 方法,1 = 参数。

【讨论】:

  • 谢谢。但我需要类似http://myurl/zurich/somecontroller/somefunction
  • 好的,@SachinStellen。我刚刚更新了我的答案。这只是一个想法,你怎么能做到这一点。也许这不是完美的方式。但只是尝试一下。 ;-)
【解决方案2】:

试试这个。 -首先告诉我你在从下拉列表中选择一个城市后如何发送请求。 - 无论如何我会告诉你,首先将 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......
}
}

【讨论】:

    猜你喜欢
    • 2020-11-17
    • 1970-01-01
    • 2016-08-29
    • 2018-10-12
    • 1970-01-01
    • 2012-04-06
    • 2019-04-29
    • 2015-11-25
    • 2013-01-03
    相关资源
    最近更新 更多