2015-11-26 40 views
0

嗨,我有一个代码,在cakephp中返回一个JSON响应,它在localhost中完美工作,但在生产中,它提供了不正确的JSON响应解析。 例如这里是我的动作代码Json数组返回生产与cakephp

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" 

我不知道是什么导致这个probleme,因为相同的代码工作在本地机器上

+0

它可能实际上有适当的细节。您的实时服务器系统可能会在日志中截断打印新行。尝试打印'json_encode($ message)' –

+0

你是什么意思的托盘打印json_encode($ message)??我应该手动构建json而不是使用json_encode? – user1655410

+0

我的意思是你尝试返回没有'JSON_PRETTY_PRINT',就像'return json_encode($ message)' –

回答

1

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

     } 

CakePHP会自动切换视图类时,请求是用.json扩展完成的,或者Accept头是application/json。

欲了解更多信息:http://book.cakephp.org/2.0/en/views/json-and-xml-views.html

+0

嗨,感谢您的回复,我现在使用json扩展,但$ this-> set('_ serialize',$ message);它会在使用.json扩展后返回一个空的响应,不像旧的 – user1655410

+0

,它在生产服务器中使用这个代码$ this-> response-> body(json_encode($ message,JSON_PRETTY_PRINT));而不是_serialize, – user1655410

+0

在你的ajax调用中,你是否也用.json扩展名调用url?如果你遵循惯例,你的代码应该是好的。 –