gpt4 book ai didi

zend-framework - Zend 应用程序 jQuery ajax 调用出现错误

转载 作者:行者123 更新时间:2023-12-01 03:52:57 25 4
gpt4 key购买 nike

我正在尝试在 Zend Framework 中使用 jQuery。我面临问题的用例是当我尝试将数据保存到数据库时。虽然数据保存在数据库中,但总是收到ajax错误。

我用来添加数据的 Controller 如下所示:

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!");
}
});
});

我总是遇到错误。

这段代码有什么问题?

提前致谢。

最佳答案

我强烈建议您实现最新的 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()

关于zend-framework - Zend 应用程序 jQuery ajax 调用出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6306028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com