【发布时间】:2023-04-10 17:13:01
【问题描述】:
我正在尝试为通过 AJAX GET 请求访问的 JSON 响应设置内容类型标头。我已经关注博客和面包店的教程,但我总是从 CakePHP 收到“文本/html”。如何正确设置 content-type 标头?
这是我目前的代码:
public function admin_controller_actions_ajax()
{
Configure::write('debug', 0);
if ($this->RequestHandler->isGet()) {
$this->autoRender = FALSE;
$aco_id = $this->params['url']['aco_id'];
$aro_id = $this->params['url']['aro_id'];
assert('$aco_id != NULL && $aro_id != NULL &&
is_numeric($aco_id) && is_numeric($aro_id)');
$actions = $this->Resource->getActionsForController($aco_id, $aro_id);
assert('is_array($actions) && is_array($actions[0])');
/* I made RequestHandler part of the $components property */
$this->RequestHandler->setContent('json');
$this->RequestHandler->respondAs('json'); /* I've tried 'json', 'JSON', 'application/json' but none of them work */
$this->set('json_content', json_encode(array('response' => $actions[0])));
$this->layout = NULL;
$this->render('/json/default');
}
}
/* json/default.ctp */
<?php echo $json_content; ?>
任何帮助将不胜感激。
谢谢,
-- 艾萨克
【问题讨论】:
-
你在你的 routes.php 文件中使用 Router::parseExtensions() 吗?如果是,则必须在 app/config/core.php 中将“debug”设置为 0,以使其响应正确的内容类型。
-
不,我不使用 Router::parseExtensions() 但无论如何我在请求中将 debug 设置为 0。
标签: php ajax json cakephp content-type