Zend应用程序jQuery ajax调用获取错误

时间:2011-06-10 11:57:15

标签: zend-framework jquery

我正在尝试使用Zend Framework中的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!");
            }
        });
  });

我总是犯错。

此代码有什么问题?

提前致谢。

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

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