Zend控制器Ajax调用面临错误



我的Zend控制器如下所示:

 public function deleteAction()
    {
        $this->_helper->layout->disableLayout();
         $id = (int)$this->_request->getPost('id');
        $costs = new Application_Model_DbTable_Costs();
        if($costs->deleteCosts($id)){
            $this->view->success = "deleted";
        }
    }

我用来发布数据的ajax调用是:

 $.ajax({
             dataType: 'json',
            url: 'index/delete',
            type: 'POST',
            data:id,
            success: function () {
             alert("success");
            },
            timeout: 13*60*1000,
            error: function(){
               console.log("Error");
            }
        });

在我的delete.html中,代码如下:

<?php 
    if($this->delete === true): 
        echo 'true';
    else:
        echo 'Sorry! we couldn't remove the source. Please try again.';
    endif;
?>

响应返回html。

这是我使用Zend Framework的第一个项目。提前谢谢。

您的控制器操作返回的是HTML,而不是JSON。

您应该考虑使用AjaxContext操作助手

public function init()
{
    $this->_helper->ajaxContext->addActionContext('delete', 'json')
                               ->initContext();
}
public function deleteAction()
{
    $id = (int)$this->_request->getPost('id');
    $costs = new Application_Model_DbTable_Costs();
    try {
        $costs->deleteCosts($id));
        $this->view->success = "deleted";
    } catch (Exception $ex) {
        $this->view->error = $ex->getMessage();
    }    
}

这里唯一需要做的另一件事是在AJAX请求中提供jsonformat参数,例如

$.post('index/delete', { "id": id, "format": "json" }, function(data) {
    if (data.error) alert("Error: " + data.error);
    if (data.success) alert("Success: " + data.success);
}, "json");

你可能想以不同的方式处理回应,但这应该会给你一个想法。

最新更新