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

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

本文介绍了如何在CakePHP中返回正确的内容类型的JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置Content-type头与一个AJAX的GET请求访问的JSON响应。我已经按照博客和面包店教程,但我总是收到text / html的从CakePHP的回来。我如何正确地设置Content-Type头?

I'm trying to set the content-type header for a JSON response accessed with an AJAX GET request. I've followed tutorials on blogs and the bakery but I always receive 'text/html' back from CakePHP. How do I set the content-type header correctly?

下面是我的code的时刻:

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

任何帮助将是AP preciated。

Any help would be appreciated.

谢谢

-艾萨克

推荐答案

阅读后和this,我得到了以下回归内容类型:应用程序/ JSON

After reading this and this, I got the following to return "Content-Type:application/json":

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

使用jQuery的$ .getJSON方法,我仍然得到

With JQuery's $.getJSON method, I'm still getting

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

但至少我的数据分析。

But at least my data is parsing.

这篇关于如何在CakePHP中返回正确的内容类型的JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:00