【发布时间】:2017-01-12 02:08:21
【问题描述】:
我正在为一个旧的 Zend Framework 1.10 项目修复一些错误,但我在重定向和页面刷新方面遇到了一些问题。
问题:进行 AJAX 调用,检查此人是否已分配保险,如果是,则在此人没有任何保险之前不允许删除此人。
解决办法:
控制器:crud/application/controllers/personController.php
class PersonController extends Zend_Controller_Action
{
// this will fetch all the persons from DB and send to the view
public function indexAction()
{
$persons = new Application_Model_DbTable_Person();
$this->view->persons = $persons->fetchAll();
}
// this will check whether the person has or not insurances
public function hasinsurancesAction()
{
$hasInsurances = new Application_Model_DbTable_Person();
return $this->_helper->json(
['count' => count($hasInsurances->personHasInsurances($this->_getParam('id')))]
);
}
...
// this will delete the person from DB and will make a redirection to indexAction
public function deleteAction()
{
if ($this->getRequest()->isPost()) {
$person_id = (int) $this->getRequest()->getPost('id');
$person = new Application_Model_DbTable_Person();
$person->deletePerson($person_id);
$this->_helper->redirector('index');
}
}
}
观点:crud/application/views/scripts/company/index.phtml
<table>
<tr>
<th>Title</th>
<th> </th>
</tr>
<?php foreach ($this->persons as $person) : ?>
<tr>
<td><?php echo $this->escape($person->title); ?></td>
<td>
<a href="<?php echo $this->url(
[
'controller' => 'person',
'action' => 'edit',
'id' => $person->id,
]
); ?>">Edit</a>
<a class="delete"
data-id="<?php echo $person->id ?>"
data-href="<?php echo $this->url(
[
'controller' => 'person',
'action' => 'delete',
'id' => $person->id,
]
); ?>"
data-delete-href="<?php echo $this->url(
[
'controller' => 'person',
'action' => 'hasInsurances',
]
); ?>"
href="#">Delete</a>
</td>
</tr>
<?php endforeach; ?>
</table>
Javascript/jQuery:crud/public/js/delete.js
$(function () {
$('.delete').on('click', function () {
id = $(this).data('id');
href_attr = $(this).data('href');
delete_attr = $(this).data('delete-href');
$.ajax({
url: delete_attr,
data: {'id': id},
success: function (result) {
if (result.count > 0) {
alert('You can not delete this person. Try deleting associated insurances first.')
} else {
$.ajax({
url: href_attr,
data: {'id': id},
type: 'POST'
});
}
}
});
})
});
问题: 上面的代码工作正常,但有一个差距,当deleteAction() 被调用并且人被删除时,它会尝试重定向到indexAction() 我仍然看到被删除的人并且我不应该。一旦我使用F5 或CTRL+R 刷新页面,该行就会消失,因为它已被删除,这应该是正确的行为。
问题:我的解决方案有什么问题?当进行第二次 AJAX 调用时,有什么方法可以从控制器或 jQuery 代码强制刷新页面?
【问题讨论】:
标签: javascript php jquery ajax zend-framework