我的控制器中有任务run。我希望它返回JSON数据。现在,我将把我的JSON数据包装在模板HTML中。如何告诉Joomla只从控制器返回JSON数据?这是我拥有的函数:
public function run ( ) {
JFactory::getDocument()->setMimeEncoding( 'application/json' );
JResponse::setHeader('Content-Disposition','attachment;filename="progress-report-results.json"');
JRequest::setVar('tmpl','component');
$data = array(
'foo' => 'bar'
);
echo json_encode( $data );
}这将返回:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb" dir="ltr">
...
</head>
<body class="contentpane">
<div id="system-message-container">
</div>
{"foo":"bar"}
</body>
</html>我想要得到:
{"foo":"bar"}发布于 2020-12-20 03:48:24
Joomla 4
您必须将参数&format=json添加到您的URL。这会告诉系统您正在等待json响应。系统将呈现JsonDocument,并将发送正确的浏览器标题作为响应。
index.php?option=com_foo&task=report.run&format=jsonclass Report extends BaseController {
public function run() {
$data = [
'foo' => 'bar'
];
$response = new ResponseJson($data);
echo $response;
}
}不需要使用$app->close();关闭应用程序,因为Joomla的架构会为您处理这一点。
如果你关闭应用程序,你会在渲染过程中错过很多东西。许多事件将不会被触发。此外,您还必须手动发送内容类型的标头。
您的代码应该如下所示。这种方法是而不是推荐的。
class Report extends BaseController {
public function run() {
$this->app->mimeType = 'application/json';
$this->app->setHeader('Content-Type', $this->app->mimeType . '; charset=' . $this->app->charSet);
$this->app->sendHeaders();
$data = [
'foo' => 'bar'
];
$response = new ResponseJson($data);
echo $response;
$this->app->close();
}
}https://stackoverflow.com/questions/16739800
复制相似问题