2011-06-12 122 views
0

我的Zend控制器是象下面這樣:的Zend控制器Ajax調用面對錯誤

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.phtml代碼如:

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

響應返回html。

它是我第一個使用Zend Framework的項目。 在此先感謝。

回答

4

您的控制器操作正在返回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請求提供的json一個format參數唯一的其他東西,如

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

您可能想要以不同的方式處理回覆,但這應該會給你一個想法。

+0

非常感謝,它工作正如你所說的,但是當我使用$ .ajax()時,它返回undefined作爲data.success.Can你解釋了什麼是錯的?它會對我有幫助,或者你可以共享一個鏈接如何jquery ajax調用zend.Thanks提前:)謝謝:) – mushfiq 2011-06-13 07:08:27

+0

得到了解決方案,我傳遞的數據格式錯誤,它應該是數據:{「id」:id},它的工作:)謝謝 – mushfiq 2011-06-13 11:12:15