问题描述:

Using PHP Zend Framework 2.0.2, I return JSON data after an AJAX call. Obviously, Internet Explorer 9 wants to download the data instead of returning it to the calling Javascript method.

Posts like this one and this one say to use Content-Type: text/plain instead of Content-Type: application/json, but how do I do this with ZF2's JsonModel? I'm new to it...

I imagine I have to set something in the setOptions() array, but what?

public function testJsonAction()

{

$jsonResponse = new JsonModel(array('success' => false));

$jsonResponse->setOptions(array(

// ** Should I put something here? What? **

));

return $jsonResponse;

}

I tried using these:

 $this->getResponse()->getHeaders()->addHeaderLine('Content-Type', 'text/plain');

$this->getResponse()->getHeaders()->addHeaderLine('Content-Disposition', 'inline; filename="textdata.json"');

but it doesn't change the HTTP Content-Type in the response headers:

Key Value

Response HTTP/1.1 200 OK

Content-Type application/json

Server Microsoft-IIS/7.5

X-Powered-By PHP/5.3.13

Set-Cookie ZDEDebuggerPresent=php,phtml,php3; path=/

Content-Disposition inline; filename="textdata.json"

X-Powered-By ASP.NET

Date Wed, 10 Oct 2012 13:19:42 GMT

Content-Length 17

Thanks for your help!

网友答案:

Because when \Zend\Mvc\MvcEvent::EVENT_RENDER event happen, the JsonStrategy will change content-type again. Source code is in

Zend\View\Strategy\JsonStrategy->injectResponse();

So in order to replace content-type into yours, you need to use EventManager to inject your custom header after JsonStrategy injected.

try below codes in your controller:

 $this->getServiceLocator()->get('Application')->getEventManager()->attach(\Zend\Mvc\MvcEvent::EVENT_RENDER, function($event){
     $event->getResponse()->getHeaders()->addHeaderLine('Content-Type', 'text/plain');
 }, -10000);
相关阅读:
Top