2011-06-10 83 views
2

我想在Zend Framework中使用jQuery。而我遇到的问题是当我试图将数据保存到数据库。尽管数据正在保存在数据库中,但始终接收到ajax错误。Zend应用程序jQuery ajax调用获取错误

,我使用添加数据控制器是象下面这样:

public function addAction() 
{ 
    // action body 
    $form = new Application_Form_Costs(); 
    $form->submit->setLabel('Add'); 
    $this->view->form = $form; 

    if($this->getRequest()->isPost()) 
    { 
     $formData = $this->getRequest()->getPost(); 
     { 
      if ($form->isValid($formData)) 
      { 
       $costTitle = $this->_request->getPost('costTitle'); 

       $costAmount = $this->_request->getPost('costAmount'); 

       $costs = new Application_Model_DbTable_Costs(); 

       if($costs->addCosts($costTitle, $costAmount)) 
       { 
        echo "suces"; 
       } 

       // $this->_helper->redirector('index'); 
      } 
      else 
      { 
       $form->populate($formData); 
      } 
     } 
    } 
} 

,这是通过数据如下jQuery的:

$('#cost').submit(function(){ 
     data = { 
     "cost_title":"cost_title", 
     "cost_amount":"cost_amount" 
    }; 

    $.ajax({ 
      dataType: 'json', 
      url: '/index/add', 
      type: 'POST', 
      data: data, 

      success: function (response) { 
      alert(response); 
      }, 

      timeout: 13*60*1000, 
      error: function(){ 
       alert("error!"); 
      } 
     }); 
    }); 

我总是得到错误。

这段代码有什么问题?

在此先感谢。

+0

检查的萤火Ajax请求......是响应有效的JSON? http://jsonlint.com – gnarf 2011-06-10 11:58:45

+0

获取整个js作为回应! – mushfiq 2011-06-10 12:13:46

+1

你能粘贴你得到的错误吗? – 2011-06-10 12:18:05

回答

3

我强烈建议你实现最新的Zend/AJAX方法。

// Inside your php controller 
public function init() 
{ 
    $ajaxContext = $this->_helper->getHelper('AjaxContext'); 
    $ajaxContext->addActionContext('add', 'json') 
       ->initContext(); 
} 

public function addAction() 
{ 
// action body 

$form = new Application_Form_Costs(); 
$form->submit->setLabel('Add'); 
$this->view->form = $form; 

if($this->getRequest()->isPost()) 
{ 
    $formData = $this->getRequest()->getPost(); 
    { 
     if ($form->isValid($formData)) 
     { 
      $costTitle = $this->_request->getPost('costTitle'); 
      $costAmount = $this->_request->getPost('costAmount'); 
      $costs = new Application_Model_DbTable_Costs(); 
      if($costs->addCosts($costTitle, $costAmount)) 
      { 
       // The view variables are returned as JSON. 
       $this->view->success = "success"; 
      } 
     } 
     else 
      { 
      $form->populate($formData); 
     } 
    } 
} 

// Inside your javascript file 
// Assign handlers immediately after making the request, 
    // and remember the jqxhr object for this request 
    var jqxhr = $.get("/index/add/format/json", function(data) { 
    alert(data); 
    }) 
    .error(function() { alert("error"); }); 

欲了解更多信息:

AjaxContext (ctrl+f)

jQuery.get()

0

我认为你在Session输出中遇到错误。你为什么不禁用视图渲染器,因为你只需要请求echo "suces"的回答,这对AJAX来说已经足够了。

+1

我已经尝试通过禁用布局,它没有工作 – mushfiq 2011-06-10 12:26:15

+0

由于,我在这里看到的唯一问题是打印布局/视图脚本的机会。你有没有在你的成功信息之后放置一个'退出'。 你有工作的例子吗? – 2011-06-10 12:30:55