Search code examples
zend-framework2jsonp

ZF2 setJsonpCallback() returns wrong content-type (application/json instead of application/javascript)


we are developing with Zend Framework 2.4 and have an API that should support jsonp callbacks.

Unfortunatelly, Chrome doesn't like the content-type it returns. It is application/json but needs to be application/javascript.

return $jsonModel->setJsonpCallback($jsonpCallback);

Is anybody aware of a ZF2 bug in that case?

Cheers


Solution

  • Unfortunately JsonStrategy doesn't look at JsonModel for a jsonp callback. If I had to guess, it's due to JsonModel not exposing the value of JsonModel::$jsonCallback. JsonStrategy will look at the renderer, JsonRenderer by default, for a jsonp callback and apply a content-type of application/javascript or application/json accordingly.

    In your situation, JsonRenderer wasn't set with a jsonp callback so JsonStrategy is returning a content-type of application/json. You can correct this by accessing the JsonRenderer from the controller and setting the jsonp callback value.

    class IndexController extends AbstractActionController
    {
        public function indexAction()
        {
            $jsonModel = new JsonModel();
            $jsonModel->setVariables(array(
                'ping' => 'pong',
            ));
    
            /** @var \Zend\View\Renderer\JsonRenderer $jsonRenderer */
            $jsonRenderer = $this->getServiceLocator()->get('ViewJsonRenderer');
            $jsonRenderer->setJsonpCallback('wakawaka');
    
            return $jsonModel;
        }
    }