【问题标题】:How to pass parameter after baseurl in codeigniter?如何在codeigniter中的baseurl之后传递参数?
【发布时间】:2019-05-25 11:03:30
【问题描述】:

基本网址:http://localhost/f1/

我在 URL 中传递参数,例如: http://localhost/f1/user1

我正在尝试打印

function index(){
    echo $this->uri->segment(2);
}

我想在控制器中打印User1。如何做到这一点?

【问题讨论】:

  • 现在,有什么问题?
  • 404 未找到显示。
  • 你设置你的base_url了吗?
  • 是的,上面我已经提到了。 localhost/f1
  • 尝试获取User1作为函数参数function index($url1){ echo $url1;}

标签: php codeigniter


【解决方案1】:

阅读这里https://www.codeigniter.com/userguide3/general/controllers.html -> Passing URI Segments to your methods

/products/shoes/sandals/123

<?php
class Products extends CI_Controller {

        public function shoes($sandals, $id)
        {
                echo $sandals;
                echo $id;
        }
}

【讨论】:

  • 如果有index方法呢?
  • 会像example.com/index.php/home/index/param1
【解决方案2】:

base_urlsegemnts/parameter之后可以变成这样

确保在application/config/config.phpapplication/config/autoload.php 文件中分别设置了base_url 和URL 助手

假设,调用一个带有锚标记

的函数
<a href="<?= base_url('HomeController/index/'.$url1)?> ">Index</a>

在上一行中,HomeController 是控制器名称,index 在函数名称中,$url1 是参数

class HomeController extends CI_Controller {

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

另外,$this-&gt;uri-&gt;segment() 也可以使用。

【讨论】:

  • 是的,正确。如果我从控制器传递参数,它会起作用,但是如果我想从 URL 传递呢?
  • URL 的登录也是一样的。
【解决方案3】:

我从您的问题中了解到,您想要重新映射而不使用您的方法并直接在您的控制器之后传递参数?

您可以使用_remap 并检查它是否正常匹配方法处理或直接将其传递给您的默认方法,现在您不需要在您的网址中使用index

public function _remap($method)
{
        if ($method === 'some_method_in_your_controller')
        {
                $this->$method();
        }
        else
        {
                $this->index($method);
        }
}

现在假设您的网址是这样的http://localhost/controller/parameter,那么如果此参数与某个方法匹配,它将调用该方法,否则它将作为参数传递给您index

【讨论】:

  • @Rishi 这就是你想要的!
【解决方案4】:

在 config/routes.php 中定义你的控制器。它会默认调用你的 index 函数。

$route['default_controller'] = 'controllername';

【讨论】:

    【解决方案5】:

    检查你是否加载了 url helper。只有这样它才能按预期工作。要么自动加载它,要么在控制器中调用它。

    【讨论】:

      【解决方案6】:

      配置您的路线并添加以下内容:

      $route['Controller_Name/(:any)'] = 'Controller_Name/index/$1';
      

      你带着你的控制器去吧

      class Controller_Name extends CI_Controller {
        function index($prm){
          echo $prm;
        }
      }
      

      玩得开心.... 你可以有多少个你想要的uri....

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-07
        • 2011-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多