简体   繁体   English

如何在CakePHP中为JSON返回正确的内容类型?

[英]How to return the correct content-type for JSON in CakePHP?

I'm trying to set the content-type header for a JSON response accessed with an AJAX GET request. 我正在尝试为使用AJAX GET请求访问的JSON响应设置content-type标头。 I've followed tutorials on blogs and the bakery but I always receive 'text/html' back from CakePHP. 我已经关注了博客和面包店的教程,但我总是从CakePHP收到'text / html'。 How do I set the content-type header correctly? 如何正确设置内容类型标题?

Here's my code at the moment: 这是我目前的代码:

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; ?>

Any help would be appreciated. 任何帮助,将不胜感激。

Thanks, 谢谢,

-- Isaac - 艾萨克

I make Ajax calls to retrieve JSON content in all of my projects and I've never done most of what you're doing here. 我进行Ajax调用以检索所有项目中的JSON内容,而且我从未完成过你在这里做的大部分工作。 The extent of my controller code looks something like this: 我的控制器代码的范围看起来像这样:

public function do_something_ajaxy() {
  Configure::write ( 'debug', 0 );
  $this->autoRender = false;

  /** Business logic as required */

  echo json_encode ( $whatever_should_be_encoded );
}

I make my Ajax calls via jQuery so I suppose that could make a difference, but it would surprise me. 我通过jQuery进行Ajax调用,所以我想这可能会有所作为,但这会让我感到惊讶。 In this case, you're problem appears to be in the handler, not with the caller. 在这种情况下,您的问题似乎出现在处理程序中,而不是调用者。 I'd recommend removing lines 17-23 and replacing them with a simple echo json_encode ( array('response' => $actions[0]) ) statement. 我建议删除第17-23行并用简单的echo json_encode ( array('response' => $actions[0]) )语句替换它们。

You're also testing for $this->RequestHandler->isGet() . 您还要测试$this->RequestHandler->isGet() Try testing $this->RequestHandler->isAjax() instead. 尝试测试$this->RequestHandler->isAjax() I'm not sure whether Ajax calls are recognized as by both their type and their method. 我不确定Ajax调用是否被它们的类型和方法识别。

After reading this and this , I got the following to return " Content-Type:application/json ": 看完这个这个 ,我得到了以下返回“ 内容类型:应用程序/ JSON”:

Configure::write('debug', 0);
$this->RequestHandler->respondAs('json');
$this->autoRender = false;            
echo json_encode($data);

With JQuery's $.getJSON method, I'm still getting 使用JQuery的$ .getJSON方法,我仍然会得到

Resource interpreted as image but transferred with MIME type text/html.

But at least my data is parsing. 但至少我的数据正在解析。

I've also just had this problem, and solved it by using: 我也遇到了这个问题,并使用以下方法解决了这个问题:

$this->RequestHandler->respondAs('text/x-json');

Also make sure that "debug" in your config file is set to less than 2 otherwise the header will not be set. 还要确保配置文件中的“debug”设置为小于2,否则将不会设置标头。

I am not sure (and, to be honest, I've never used CakePHP), but you may want to try to specify a second argument in the setContent method.. 知道(而且,说实话,我从来没有使用CakePHP的),但你可能要尝试指定的setContent方法的第二个参数..

replace this: 替换这个:

$this->RequestHandler->setContent('json') 

with this: 有了这个:

$this->RequestHandler->setContent('json', 'text/x-json');

see this file for an example.. 请参阅此文件以获取示例..

I've been having the same problem as the original poster, and what worked for me was to follow Rob Wilkerson's advice, but also make sure I was using 我一直遇到和原版海报一样的问题,对我有用的是跟随Rob Wilkerson的建议,但也要确保我在使用

jQuery.ajax()

instead of 代替

jQuery.get()

or 要么

jQuery.post()

jQuery.ajax() allows you to set the dataType to 'json' whereas the other two don't seem to allow you to set the datatype at all. jQuery.ajax()允许您将dataType设置为'json',而其他两个似乎根本不允许您设置数据类型。 When I set the data type in the AJAX request to 'json' it all worked as it should. 当我将AJAX请求中的数据类型设置为'json'时,它都按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM