pal*_*laa 4 ajax json zend-framework
我想向控制器发送Ajax请求,我在客户端这样做
jQuery.ajax({
url: "public/visits/visit/get-visits",
type: "POST",
dataType: 'json',
data: data,
success: function(data){
alert(data)
},
error:function(){
alert("fail :(");
}
});
Run Code Online (Sandbox Code Playgroud)
在服务器端,我处理请求作为其他请求
public function getVisitsAction() {
if (isset($_POST)) {
$mapper = new Visits_Model_VisitsMapper();
$allVisits = $mapper->getAllVisits();
echo json_encode($allVisits);
}
Run Code Online (Sandbox Code Playgroud)
当我调用该操作时,会发生失败警报,当我通过防火错误检查出来时,我发现它将json数据返回给客户端到页面get-visit.phtml.
如何从发送json请求的页面处理成功函数中的响应并将其重定向到get-visit.phtml页面?
小智 19
Zend有Zend_Controller_Action_Helper_Json执行以下操作:
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
echo json_encode($allVisits);
exit;
Run Code Online (Sandbox Code Playgroud)
所以它可能更简单:
public function getVisitsActions() {
if ($this->getRequest()->isXmlHttpRequest()) {
if ($this->getRequest()->isPost()) {
$mapper = new Visits_Model_VisitsMapper();
$this->_helper->json($mapper->getAllVisits());
}
}
else {
echo 'Not Ajax';
// ... Do normal controller logic here (To catch non ajax calls to the script)
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
为了更正确的方式这样做.我会在你的控制器中使用以下内容
public function getVisitsActions() {
if ($this->getRequest()->isXmlHttpRequest()) {
if ($this->getRequest()-isPost()) {
$mapper = new Visits_Model_VisitsMapper();
$allVisits = $mapper->getAllVisits();
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
echo json_encode($allVisits);
exit;
}
}
else {
// ... Do normal controller logic here (To catch non ajax calls to the script)
}
}
Run Code Online (Sandbox Code Playgroud)