Since you are using the Phalcon framework, I would recommend that you use the built-in features to properly handle json responses:
$this->response->setContentType('application/json', 'UTF-8'); $this->response->setJsonContent($responseAsArray); $this->response->send();
If the application/json header is included in the response, jQuery starts processing it correctly and you do not need JSON.parse your frame.
To handle json responses in an API module in one of my applications, I have a ControllerBase that extends \Phalcon\Mvc\Controller with this event handler:
use \Phalcon\Mvc\Controller; class ControllerBase extends Controller { /** * Captures method result and tries to make a JSON response out of it. * * @param \Phalcon\Mvc\Dispatcher $dispatcher * @return \Phalcon\Http\Response */ protected function afterExecuteRoute($dispatcher) { $content = $dispatcher->getReturnedValue(); if(is_object($content)) { if(is_callable(array($content, 'toArray'))) { $content = $content->toArray(); } else { $content = (array) $content; } } $frame = $this->getFrame($content, $dispatcher); // protocol frame creation helper $this->response->setContentType('application/json', 'UTF-8'); switch($frame['code']) { case 200: $this->response->setStatusCode(200, 'OK'); break; case 400: $this->response->setStatusCode(404, 'Not found'); break; case 500: $this->response->setStatusCode(503, 'Service Unavailable'); break; } // clearing potential warnings $ob = ob_get_clean(); if(strlen($ob) > 0) { /** * @todo some logging of $ob ! * this will be a dead code if you will make an Error2Exception handler */ echo($ob); die(); } // settinf response content as JSON $this->response->setJsonContent($frame); return $this->response->send(); } }
source share