02. Laravel 4 响应

本文介绍了使用Laravel框架进行视图渲染及响应处理的方法,包括基本的视图展示、向视图传递数据、实现页面重定向以及如何定制HTTP响应等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

视图响应

模板文件:

<!-- app/views/simple.php -->
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Views!</title>
</head>
<body>
    <p>Oh yeah! VIEWS!</p>
</body>
</html>

路由定义:

// app/routes.php
Route::get('/', function()
{
    return View::make('simple');
});
向视图中传递数据
// app/routes.php
Route::get('/{squirrel}', function($squirrel)
{
    $data['squirrel'] = $squirrel;
    return View::make('simple', $data);
});

<!-- app/views/simple.php -->
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Squirrels</title>
</head>
<body>
    <p>I wish I were a <?php echo $squirrel; ?> squirrel!</p>
</body>
</html>

重定向

// app/routes.php
Route::get('first', function()
{
    return Redirect::to('second');
});
Route::get('second', function()
{
    return 'Second route.';
});
重定向在用户认证中的应用
// app/routes.php
Route::get('books', function()
{
    if (Auth::guest()) return Redirect::to('login');
    // Show books to only logged in users.
});

可定制的服务器响应

定制响应的“头信息”
// app/routes.php
Route::get('markdown/response', function()
{
    $response = Response::make('***some bold text***', 200);
    $response->headers->set('Content-Type', 'text/x-markdown');
    return $response;
});
定制响应的“存活时间”

存活时间 Time-to-live 这个时间以秒为单位,它是数据包可以生存的时间。在传输中,如果超过了这个时间,这个数据报就被认为丢失了,或在一个循环内并且被废弃。

// app/routes.php
Route::get('our/response', function()
{
    $response = Response::make('Bond, James Bond.', 200);
    $response->setTtl(60);
    return $response;
});

Response 的 API

请参考 TheSymfonyResponseObject

Respanse 的快捷方法

JSON 响应
// app/routes.php
Route::get('markdown/response', function()
{
    $data = array('iron', 'man', 'rocks');
    return Response::json($data);
});

浏览器将输出 ["iron","man","rocks"]

下载 响应
// app/routes.php
Route::get('file/download', function()
{
    $file = 'path_to_my_file.pdf';
    return Response::download($file);
});

可定制 HTTP 状态码、头信息

// app/routes.php
Route::get('file/download', function()
{
    $file = 'path_to_my_file.pdf';
    return Response::download($file, 418, array('iron', 'man'));
});

转载于:https://my.oschina.net/5say/blog/186238

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值