【问题标题】:CakePHP passing arguments in Controller::redirectCakePHP 在 Controller::redirect 中传递参数
【发布时间】:2012-06-24 11:42:29
【问题描述】:

在进行重定向的控制器操作中,我使用了这个:

$this->redirect(array('controller' => 'tools', 'action' => 'index'));

或者这个

$this->redirect('/tools/index');

当我通过重定向传递数据时,我使用这个:

$this->redirect('tools/index/?myArgument=12');

但我找不到如何通过“this-redirect-array”表示法传递“myargument”。
我不想使用它,因为一些路由问题:

$this->redirect(array('controller' => 'tools', 'action' => 'index', "myArgument"));

我需要这样的东西:

$this->redirect(array('controller' => 'tools', 'action' => 'index', "?myArgument=12"));

【问题讨论】:

  • 正如 Jleagle 所展示的,可以使用数组概念来创建标准 RFC 3986 查询字符串,但这通常不是一个好主意。您是否有不想使用 Cake 的友好 URL 路由的特殊原因?

标签: php cakephp redirect cakephp-2.0


【解决方案1】:

Cake 确实支持使用问号的查询参数,如下所示:

$this->redirect(array(
    'controller' => 'tools', 'action' => 'index', '?' => array(
        'myArgument' => 12
    )
));

http://book.cakephp.org/2.0/en/development/routing.html#reverse-routing

但最好还是像des说的那样做:

$this->redirect(array(
    'controller' => 'tools', 'action' => 'index', 'myArgument' => 12
));

【讨论】:

  • 正确,我不知道'?'可以用来做这个。
【解决方案2】:

这应该可行:

$this->redirect(array('controller' => 'tools', 'action' => 'index', 'myArgument' => 12));

看看CakePHP Cookbook - Controller::redirect

Accessing request parameters:

$this->request['myArgument'];
$this->request->myArgument;
$this->request->params['myArgument'];

【讨论】:

  • 好吧,该解决方案将创建这个:“tools/index/myArgument:12” 但我需要这个:“tools/index/?myArgument=12"
  • 有什么原因吗?您可以使用$this->params['named'] 访问该参数。根据您传递额外参数的方式,取决于输出的 URL。 More in the manual
  • @trante 我编辑了我的答案,向您展示如何访问此参数。我认为没有理由将 CakePHP 路由与经典查询字符串混合。这有什么具体原因吗? @Ross 很好的评论,但问题是 CakePHP2 ;)
  • @des 因为我不想只为一种情况更改太多路由代码:) :)
  • @trante simple 你可以用吗? $this->redirect(array('controller' => 'tools', 'action' => 'index', '?' => array('variableName' => 'variableValue'))); 然后在行动索引中你可以使用$variableValue = $this->request->query('variableName');
【解决方案3】:

使用它来重定向:

$this->redirect(array('controller' => 'tools', 'action' => 'index', 'myArgument' => 12));

和 Router::connectNamed() 到 router.php 以将分隔符从“:”更改为“=”:

Router::connectNamed(
    array('myArgument' => array('action' => 'index', 'controller' => 'tools')), array('default' => false, 'greedy' => false, 'separator' => '=')

);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2014-02-12
    • 2015-10-10
    相关资源
    最近更新 更多