这两天接触一套用Zend框架开发的商城系统,在后台新增加了一个action后,前端发送ajax请求里,后端的action总是报这个错误:
Fatal error: Uncaught exception 'Zend_Controller_Dispatcher_Exception' with message 'Invalid controller specified (error)'
Fatal error: Uncaught exception 'Zend_Controller_Dispatcher_Exception' with message 'Invalid controller specified (error)'
经过分析发现原来zend的框架对于ajax的请求需要这样处理:
public function ajaxAction(){
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$this->getResponse()->setHeader("Content-type", "text/json");
$this->_helper->json->suppressExit = true;
$result = ['code'=>0,'msg'=>'','data'=>[]];
//业务处理过程
$this->_helper->json($result);
}
注意的是在这个ajax响应的action里最开始需要加上:
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$this->getResponse()->setHeader("Content-type", "text/json");
$this->_helper->json->suppressExit = true;
$this->_helper->json($result);
并且最后 一行不能加return ,如果加return 会报错
用来禁用Layout和模板
$this->_helper->layout->disableLayout();
调用"disableLayout“让你的控制器不再寻找模板
$this->_helper->viewRenderer->setNoRender();
对"setNoRender“的调用使您不再查找视图脚本
$this->getResponse()->setHeader("Content-type", "text/json");
调用"setHeader“将为json设置内容类型
$this->_helper->json->suppressExit = true;
将suppressExit设置为true调用"_helper->json“不退出ZF调度循环,否则不会调用"postDispatch”
如有问题,欢迎大家留言沟通,点赞支持!!