嗨,我有一个代码在cakepp中返回json响应,它在localhost中运行良好,但在生产中,它没有提供格式良好的json响应来解析。例如,这是我的动作代码
public function deletepic(){
///configuration de l'ajax
$this->autoRender = false;
$this->request->allowMethod(array('ajax'));
$message = array('key'=>'hello');
if($this->request->is(array('ajax'))){
$picid = $this->request->data['id'];
$picname = $this->request->data['attachmentname'];
if($this->Profile->deleteAll(array('Pic.id'=>$picid,'Pic.attachment'=>$picname),false)){
$message = array('info'=>'good');
}
else{
$message = array('info'=>'bad');
}
}
$this->response->type = 'json';
return json_encode($message, JSON_PRETTY_PRINT);
}
它为我返回以下json响应:
{
"info"
我不知道是什么导致了这个问题,因为相同的代码在本地机器上工作
CakePHP已经在JsonView类中构建。你可以做下面这样的事情。
在Config/routes.php文件中,添加以下代码行:
Router::parseExtensions('json');
并且像这样覆盖你的代码:
public function deletepic(){
///configuration de l'ajax
$this->autoRender = false;
$this->request->allowMethod(array('ajax'));
$message = array('key'=>'hello');
if($this->request->is(array('ajax'))){
$picid = $this->request->data['id'];
$picname = $this->request->data['attachmentname'];
if($this->Profile->deleteAll(array('Pic.id'=>$picid,'Pic.attachment'=>$picname),false)){
$message = array('info'=>'good');
}
else{
$message = array('info'=>'bad');
}
}
$this->set('_serialize', $message);
}
当使用.json扩展名完成请求时,或者Accept头是application/json时,CakePHP将自动切换视图类。
有关更多信息:http://book.cakephp.org/2.0/en/views/json-and-xml-views.html