首页 > 解决方案 > Yii2获取参数问题

问题描述

我的问题是,我将?在 get 参数名称的开头加上。例如,如果 url 是

https://example.com/path?id=2

我会得到一个名为?id.How 的 get 参数,id?不是使用这种方式:

https://example.com/path?&id=2

它是有线的:)

---------------- 这里是详细信息----------------

url 管理器配置:

[
    'urlManager' => [
        'enablePrettyUrl'   => true,
        'showScriptName'    => false,
        'rules' => [
            [
                'pattern'   => '<lang:(zh|en)>/login',
                'route'     => 'account/default/login',
            ],
            [
                'pattern'   => '<lang:(zh|en|api)>/<modules>/<controller>/<action>',
                'route'     => '<modules>/<controller>/<action>',
                'defaults'  => [
                    'lang'      => 'zh',
                    'modules'   => 'dashboard',
                    'controller'=> 'default',
                    'action'    => 'index',
                ],
            ],
        ],
    ],
];

你看,我会用这个lang参数来控制网站的语言版本。我发现Yii会把它lang当作一个get参数来处理。所以这就是问题所在。lang可能是第一个 get 参数,因此 php 将其?作为参数名称的一部分进行处理。

如果我打印获取参数,我会得到这个。

https://example.com/en/modules/controller/action?id=1

代码如下:

var_dump(\Yii::$app->request->get());

它将打印:

array(2) { ["lang"]=> string(3) "en" ["?id"]=> string(1) "1" }

多谢。

标签: phpwebyii2yii-url-manager

解决方案


ID在要匹配的模式中包含参数。

[
    'urlManager' => [
        'enablePrettyUrl'   => true,
        'showScriptName'    => false,
        'rules' => [
            [
                'pattern'   => '<lang:(zh|en)>/login',
                'route'     => 'account/default/login',
            ],
            [
                // Add the id to the pattern in the following line
                'pattern'   => '<lang:(zh|en|api)>/<modules>/<controller>/<action>/<id:\d+>',
                'route'     => '<modules>/<controller>/<action>',
                'defaults'  => [
                    'lang'      => 'zh',
                    'modules'   => 'dashboard',
                    'controller'=> 'default',
                    'action'    => 'index',
                ],
            ],
        ],
    ],
];

pattern将元素更改为以下内容:

'pattern' => '<lang:(zh|en|api)>/<modules>/<controller>/<action>/<id:\d+>',

将在斜线后捕获一个数字,并将其作为$id方法参数提供给您的操作。

如果您想使用问号而不是斜线来将操作与参数分开,我您可以使用以下模式:

'pattern' => '<lang:(zh|en|api)>/<modules>/<controller>/<action>?<id:\d+>'

但我还没有尝试过。


推荐阅读