如何使用 Silverstripe Controller 默认 return JSON?
How to return JSON by default with Silverstripe Controller?
我们有一个 class 扩展 \PageController
并且有一个 allowed action
到 return JSON。下面是一些示例代码:
class CustomController extends PageController
{
private static $allowed_actions = array(
'json'
);
public function json(HTTPRequest $request)
{
$data['ID'] = $this->ID;
$data['Title'] = $this->Title;
$data['Content'] = $this->Content;
$this->response->addHeader('Content-Type', 'application/json');
return json_encode($data);
}
}
当调用 https://www.example.com/custom/json
时,它 return 是一个 JSON 包含一些页面信息的对象。
默认使用此控制器 return JSON 的最佳方式是什么?
在上面的例子中我们想要https://www.example.com/custom
到return一个JSON对象。
原来我需要做的就是将方法名称从 json
更改为 index
:
public function index(HTTPRequest $request)
{
$data['ID'] = $this->ID;
$data['Title'] = $this->Title;
$data['Content'] = $this->Content;
$this->response->addHeader('Content-Type', 'application/json');
return json_encode($data);
}
我们有一个 class 扩展 \PageController
并且有一个 allowed action
到 return JSON。下面是一些示例代码:
class CustomController extends PageController
{
private static $allowed_actions = array(
'json'
);
public function json(HTTPRequest $request)
{
$data['ID'] = $this->ID;
$data['Title'] = $this->Title;
$data['Content'] = $this->Content;
$this->response->addHeader('Content-Type', 'application/json');
return json_encode($data);
}
}
当调用 https://www.example.com/custom/json
时,它 return 是一个 JSON 包含一些页面信息的对象。
默认使用此控制器 return JSON 的最佳方式是什么?
在上面的例子中我们想要https://www.example.com/custom
到return一个JSON对象。
原来我需要做的就是将方法名称从 json
更改为 index
:
public function index(HTTPRequest $request)
{
$data['ID'] = $this->ID;
$data['Title'] = $this->Title;
$data['Content'] = $this->Content;
$this->response->addHeader('Content-Type', 'application/json');
return json_encode($data);
}