php - 如何告诉 ZF2 的 JsonModel 返回 text/plain 而不是 application/json?

标签 php json zend-framework2

使用 PHP Zend Framework 2.0.2,我在 AJAX 调用后返回 JSON 数据。显然,Internet Explorer 9 想要下载数据而不是将其返回给调用 Javascript 方法。

类似 this one 的帖子和 this one说要使用 Content-Type: text/plain 而不是 Content-Type: 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"');

但它不会更改响应 header 中的 HTTP Content-Type:

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_RENDER 事件发生时,JsonStrategy 将再次改变内容类型。源代码在

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

因此,为了将内容类型替换为您的内容类型,您需要使用 EventManager 在 JsonStrategy 注入(inject)后注入(inject)您的自定义 header 。

在您的 Controller 中尝试以下代码:

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

关于php - 如何告诉 ZF2 的 JsonModel 返回 text/plain 而不是 application/json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12820415/

相关文章:

php - 从 php 检索数据库权限?

json - R:将 JSON 通用扁平化为 data.frame

zend-framework2 - 在 FirePHP 记录器上显示对象

php - 连接 phpMyAdmin MySQL 数据库时出现问题

php - 正则表达式是否足够或我需要更多检查?

php - mysql/php 搜索标签引擎

mysql - 从 ZF2 中的 mysql 查询获取结果

javascript - 如何将小文本文件的内容加载到 javascript var wo/JQuery 中?

读取 Hive 表中的 JSON 数据

php - 如何从 View 模块获取 $_POST 请求?