yii2利用response对象,返回指定数据格式

来源:互联网 发布:kdl 55w800a 装软件 编辑:程序博客网 时间:2024/05/06 09:53

当应用完成处理一个请求后, 会生成一个[[yii\web\Response|response]]响应对象并发送给终端用户 响应对象包含的信息有HTTP状态码,HTTP头和主体内容等, 网页应用开发的最终目的本质上就是根据不同的请求构建这些响应对象。

在大多是情况下主要处理继承自 [[yii\web\Response]] 的 response 应用组件, 尽管如此,Yii也允许你创建你自己的响应对象并发送给终端用户

首先在命名空间下引用Response类;use yii\web\Response; 

1、发送http状态码

    Yii_>$app->response->statusCode;

发送http请求状态后,执行的状态操作如下:

  • [[yii\web\BadRequestHttpException]]: status code 400.
  • [[yii\web\ConflictHttpException]]: status code 409.
  • [[yii\web\ForbiddenHttpException]]: status code 403.
  • [[yii\web\GoneHttpException]]: status code 410.
  • [[yii\web\MethodNotAllowedHttpException]]: status code 405.
  • [[yii\web\NotAcceptableHttpException]]: status code 406.
  • [[yii\web\NotFoundHttpException]]: status code 404.
  • [[yii\web\ServerErrorHttpException]]: status code 500.
  • [[yii\web\TooManyRequestsHttpException]]: status code 429.
  • [[yii\web\UnauthorizedHttpException]]: status code 401.
  • [[yii\web\UnsupportedMediaTypeHttpException]]: status code 415.

发送http 404状态码

        
  function actionCate($id){             $data= Cate::find()->where(['cid' =>$id])->one();              if(false==$data){      Yii:$app->response->statusCode=404;                   throw new NotFoundHttpException(404);                   exit(0);             }}



发送headers请求【请求网页,字符集为utf-8】
                
$headers=Yii::$app->response->headers;  $headers->add("Content-type","text/html;charset=utf-8");  print_r($data->news);



2、发送指定格式json,xml,html,jsonp

function actionCate($id){$data= Cate::find()->where(['cid' =>$id])->one();if(false==$data){Yii:$app->response->statusCode=404;throw new NotFoundHttpException(404);exit(0);}        //利用response,发送json格式数据        $response=Yii::$app->response;        $response->format=Response::FORMAT_JSON;        $response->data=$data->news;}



3、实现浏览器状态码跳转[301,302]

 
 Yii::$app->response->redirect("http://www.qq.com",301)->send();    public function actionGo(){return $this->redirect('http://www.qq.com',301);      }



4、实现文件的发送
Yii::$app->response->sendFile("/html/book/i.txt")->send();





1 0