警告-此页面上的某些功能需要的浏览器或操作系统比您当前使用的浏览器或操作系统更新。 请在其他浏览器打开该页面。
使用HTTP响应对象
API文档响应
示例代码
// Sending a response using the Application Object. By default when a
// string is returned in a route the server returns an HTML response.
$app->get('/app-html', function() {
return '<h1>Hello World</h1>';
});
// The Response Object provides many options such as cache control headers
// and secure cookies. This example shows a basic HTML response
// by setting [content()] and returning the Response Object.
$app->get('/res-html', function() {
$res = new \FastSitePHP\Web\Response();
$res->content('<h1>Hello World</h1>');
return $res;
});
// Return a JSON Response by returning an Object or an Array
$app->get('/app-json-object', function() {
$object = new \stdClass;
$object->greeting = 'Hello World';
return $object;
});
$app->get('/app-json-array', function() {
return ['greeting' => 'Hello World'];
});
// Send JSON using the Response Object
$app->get('/res-json', function() {
$res = new \FastSitePHP\Web\Response();
// Set the 'Content-Type' Header.
// The following 3 function calls all set the same value.
// The difference is that [contentType()] is a helper function
// which allows for short-hand values of
// [html, json, jsonp, text, css, javascript, xml].
$res->contentType('json');
$res->contentType('application/json');
$res->header('Content-Type', 'application/json');
// For JSON Content either Objects and Arrays are used
$data = ['greeting' => 'Hello World'];
$res->content($object);
// The helper [json()] can improve code readability as it
// sets both [contentType()] and [content()].
$res->json($data);
return $res;
});
// The Application Object allows for basic Response Headers using the
// [header()] function. This helps avoid creating a Response Object if it
// is not needed, however a response object may be preferred for clarity.
$app->get('/app-text', function() {
$app->header('Content-Type', 'text/plain');
return 'Hello World';
});
// When using the Response Object, properties are set through
// getter/setter functions and are chainable.
$app->get('/res-text', function() {
return (new \FastSitePHP\Web\Response())
->contentType('text')
->content('Hello World');
});