How to say ZF2 JsonModel return text / plain instead of application / json?

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

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

I assume I need 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 does not 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 

Thank you for your help!

+4
source share
1 answer

Because when the \ Zend \ Mvc \ MvcEvent :: EVENT_RENDER event occurs, JsonStrategy will again change the content type. The source code is in

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

So, to replace the content type with yours, you need to use the EventManager to enter a custom title after entering JsonStrategy.

try entering the codes in the controller:

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

Source: https://habr.com/ru/post/1438902/


All Articles