Php 如何告诉ZF2';s JsonModel是否返回text/plain而不是application/json?

Php 如何告诉ZF2';s JsonModel是否返回text/plain而不是application/json?,php,json,zend-framework2,Php,Json,Zend Framework2,使用PHPzendFramework2.0.2,我在AJAX调用后返回JSON数据。显然,InternetExplorer9希望下载数据,而不是将其返回给调用Javascript方法 帖子喜欢并说使用内容类型:text/plain而不是内容类型:application/json,但是如何使用ZF2的JsonModel呢?我是新手 我想我必须在setOptions()数组中设置一些东西,但是什么呢 public function testJsonAction() { $jsonRespons

使用PHPzendFramework2.0.2,我在AJAX调用后返回JSON数据。显然,InternetExplorer9希望下载数据,而不是将其返回给调用Javascript方法

帖子喜欢并说使用
内容类型:text/plain
而不是
内容类型:application/json
,但是如何使用ZF2的JsonModel呢?我是新手

我想我必须在
setOptions()
数组中设置一些东西,但是什么呢

public function testJsonAction()
{
   $jsonResponse = new JsonModel(array('success' => false));

   $jsonResponse->setOptions(array(
         // ** Should I put something here? What? **
   ));

   return $jsonResponse;
}
我试着使用这些:

  $this->getResponse()->getHeaders()->addHeaderLine('Content-Type', 'text/plain');
  $this->getResponse()->getHeaders()->addHeaderLine('Content-Disposition', 'inline; filename="textdata.json"');
但它不会更改响应头中的HTTP内容类型:

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

谢谢你的帮助

因为当\Zend\Mvc\MvcEvent::EVENT\u RENDER事件发生时,JsonStrategy将再次更改内容类型。源代码在中

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

因此,为了将内容类型替换为您的内容类型,您需要在注入JsonStrategy之后使用EventManager注入您的自定义头

在控制器中尝试以下代码:

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

谢谢,但它没有工作,它仍然是
application/json
。我在你提到的函数中设置了断点,我看到它是在调用附加事件之后调用的。。。在这一点之后,标题包含了内容类型键的3倍。您好!我尝试将event函数附加到
MvcEvent::event\u FINISH
事件,但它成功了!在你看来,有什么理由不这样做吗?嗨,实际上我只是在ViewModel中测试了我的代码,它工作了,刚才我测试了JsonViewModel,我发现事件优先级不够小,我将它调整为-10000,它工作了。我没有使用EVENT_FINISH,因为JsonStrategy在EVENT_RENDER中更改了头,只是为了减少入侵。谢谢!成功了。但是,我确实必须在事件函数中为
$event
更改
$this
,否则我会在不在对象上下文中时使用$this得到
错误…在我的开发环境中,使用$this是可以的,没有任何警告,可能这与php版本有关,我的php是5.4.4