使用 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/