PHP Class Cake\View\JsonView
It allows you to omit templates if you just need to emit JSON string as response.
In your controller, you could do the following:
$this->set(['posts' => $posts]);
$this->set('_serialize', true);
When the view is rendered, the
$posts view variable will be serialized
into JSON.
You can also set multiple view variables for serialization. This will create
a top level object containing all the named view variables:
$this->set(compact('posts', 'users', 'stuff'));
$this->set('_serialize', true);
The above would generate a JSON object that looks like:
{"posts": [...], "users": [...]}
You can also set
'_serialize' to a string or array to serialize only the
specified view variables.
If you don't use the
_serialize, you will need a view template. You can use
extended views to provide layout-like functionality.
You can also enable JSONP support by setting parameter
_jsonp to true or a
string to specify custom query string parameter name which will contain the
callback function name.
ファイルを表示
Open project: cakephp/cakephp
Class Usage Examples
Public Properties
Property |
Type |
Description |
|
$layoutPath |
string |
JSON layouts are located in the json sub directory of Layouts/ |
|
$subDir |
string |
JSON views are located in the 'json' sub directory for controllers' views. |
|
Protected Properties
Public Methods
Protected Methods
Method Details
_dataToSerialize()
protected method
Returns data to be serialized.
_serialize()
protected method
### Special parameters
_jsonOptions You can set custom options for json_encode() this way,
e.g. JSON_HEX_TAG | JSON_HEX_APOS.
protected _serialize ( array | string | boolean $serialize ) : string | false |
$serialize |
array | string | boolean |
The name(s) of the view variable(s)
that need(s) to be serialized. If true all available view variables. |
return |
string | false |
The serialized data, or boolean false if not serializable. |
### Special parameters
_serialize To convert a set of view variables into a JSON response.
Its value can be a string for single variable name or array for multiple
names. If true all view variables will be serialized. It unset normal
view template will be rendered.
_jsonp Enables JSONP support and wraps response in callback function
provided in query string.
- Setting it to true enables the default query string parameter "callback".
- Setting it to a string value, uses the provided query string parameter
for finding the JSONP callback name.
Property Details
$_responseType protected_oe property
protected string $_responseType |
return |
string |
|
$_specialVars protected_oe property
List of special view vars.
protected array $_specialVars |
return |
array |
|
$layoutPath public_oe property
JSON layouts are located in the json sub directory of Layouts/
public string $layoutPath |
return |
string |
|
$subDir public_oe property
JSON views are located in the 'json' sub directory for controllers' views.
public string $subDir |
return |
string |
|