10 php ajax json content-type cakephp
我正在尝试为使用AJAX GET请求访问的JSON响应设置content-type标头.我已经关注了博客和面包店的教程,但我总是从CakePHP收到'text/html'.如何正确设置内容类型标题?
这是我目前的代码:
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; ?>
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激.
谢谢,
- 艾萨克
我进行Ajax调用以检索所有项目中的JSON内容,而且我从未完成过你在这里做的大部分工作.我的控制器代码的范围看起来像这样:
public function do_something_ajaxy() {
Configure::write ( 'debug', 0 );
$this->autoRender = false;
/** Business logic as required */
echo json_encode ( $whatever_should_be_encoded );
}
Run Code Online (Sandbox Code Playgroud)
我通过jQuery进行Ajax调用,所以我想这可能会有所作为,但这会让我感到惊讶.在这种情况下,您的问题似乎出现在处理程序中,而不是调用者.我建议删除第17-23行并用简单的echo json_encode ( array('response' => $actions[0]) )语句替换它们.
你也在测试$this->RequestHandler->isGet().尝试测试$this->RequestHandler->isAjax().我不确定Ajax调用是否被它们的类型和方法识别.
看完这个和这个,我得到了以下返回" 内容类型:应用程序/ JSON ":
Configure::write('debug', 0);
$this->RequestHandler->respondAs('json');
$this->autoRender = false;
echo json_encode($data);
Run Code Online (Sandbox Code Playgroud)
使用JQuery的$ .getJSON方法,我仍然会得到
Resource interpreted as image but transferred with MIME type text/html.
Run Code Online (Sandbox Code Playgroud)
但至少我的数据正在解析.
我不确定(说实话,我从未使用过 CakePHP),但您可能想尝试在 setContent 方法中指定第二个参数。
替换这个:
$this->RequestHandler->setContent('json')
Run Code Online (Sandbox Code Playgroud)
有了这个:
$this->RequestHandler->setContent('json', 'text/x-json');
Run Code Online (Sandbox Code Playgroud)
请参阅此文件的示例..
| 归档时间: |
|
| 查看次数: |
13725 次 |
| 最近记录: |