Analysis Yii frame assembly in response to usage example

When we come to the browser sends a request, which in our operation request After treatment, the results of our server also packaged into a request message, then the message is returned to the browser, we call this message response. In our operations, we can set some response and processing. To deal with our response, we need to get this thing in response components.

?
1
$response = \Yii:: $app ->response;

With this response components After that, we can make some set up to respond to the message, such as setting the status code of the response.

?
1
2
3
$response ->setStatusCode(404);
//两种方法都可以设置
$response ->statusCode = '404' ;

This time when we come to visit, 404 errors occur, open developer debugging tool, but also can see the status code 404 in the following network options

Write pictures described here

We can also add some header information

?
1
2
//禁止浏览器缓存我们的消息
$response ->headers->add( "pragma" , "no-cache" );

After refreshing again, we can see in the header information pragma: no-cache of words, and this time the browser will not cache our message.

Similarly, we can also modify header information

?
1
2
//告诉浏览器收到我们的消息后把我们的消息缓存5秒钟
$response ->headers->set( "pragma" , "max-age=5" );

After refreshing, we can see our pragma field really programmed max-age = 5. 
Similarly, we can also remove some of the information.

?
1
$response ->headers->remove( "pragma" );

http head, there are many interesting features, such as file downloads

?
1
$response ->headers->add( "content-disposition" , "attachment;filename='abc.jpg'" );

After refreshing your browser, we can see the abc.jpg browser to download files. 
This feature is commonly used to download files, so in response to our packaging in a way, sendFile

?
1
$response ->sendFile( './favicon.ico' );

Refresh browser to download favicon.ico can see this file in the current directory, if the file does not exist it will error. 

Guess you like

Origin www.cnblogs.com/yscgda54/p/11503348.html