yii通过请求组件处理get,post请求

在控制器的操作中处理get,post请求时,首先需要获得请求组件。

$request = \Yii::$app->request;

得到这个请求组件后,我们就可以通过请求组件获得参数了。

//通过get获取参数
$id = $request->get("id");
//通过post获取参数
$id = $request->post("id");

在Yii框架中,我们不仅可以获取参数,还可以设置默认值,如果传参中没有这个参数,则会返回默认值。

//为get,post两种方法设置默认参数10
$id = $request->get("id",10);
$id = $request->post("id",10);

这时如果访问http://basic/web/index.php?r=index/say?num=20时,因为参数中并没有id,$id会获取默认值10。

在这个$request组件中,还提供了基本的判断等,比如判断请求的方式。

if($request->isGet){
    echo "this is Get";
}else if ($request->isPost){
    echo "this is Post";
}

如果请求时Get方式,就会打印出this is Get,如果是Post,则会输出this is Post。

通过请求组件还可以获取用户的ip地址等信息,这里以IP地址为例

$user_ip = $request->userIP;

猜你喜欢

转载自blog.csdn.net/qq_18335837/article/details/80293491