2016-09-04 3 views
0

Я работаю над некоторыми исправлениями ошибок для старого проекта 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>&nbsp;</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, строка исчезает, потому что она была удалена, и это должно быть правильное поведение.

Вопрос: Что не так в моем решении? есть ли способ принудительного обновления страницы либо с контроллера, либо с помощью кода jQuery при выполнении второго вызова AJAX?

ответ

1

Если delete_attr является URL, который делает вызов PersonController->deleteAction() ваша проблема заключается в том, что ваш браузер делает запрос Ajax (который перенаправляется), но возвращаемые данные получают обратно в Ajax вызова (success: function (result) {) и страницу пользователь это то же самое.

Что вы можете сделать, это добавить новую переменную (do_redirect => true) и URL, который вы хотите перенаправить пользователя, и если ваша функция успеха получить, что URL-адрес - он должен сделать редирект:

class PersonController extends Zend_Controller_Action { 
    ... 
    // this will delete the person from DB and will make a redirection to indexAction 
    public function deleteAction() 
    { 
     if ($this->getRequest()->isPost()) { 
      ... 
      $person->deletePerson($person_id); 

      return $this->_helper->json(
       ['do_redirect' => TRUE, 'redirect_url' => 'index.php'] 
      ); 
     } 
    } 
} 

И в вашем ajax-вызове вы должны проверить do_redirect:

$.ajax({ 
    url: delete_attr, 
    data: {'id': id}, 
    success: function (result) { 
     if ('do_redirect' in result && 'redirect_url' in result) { 
      window.location.href = result.redirect_url 
     } 
     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', 
       success: function(result) { 
        if ('do_redirect' in result && 'redirect_url' in result) { 
         window.location.href = result.redirect_url 
        } 
       } 
      }); 
     } 
    } 
}); 
Смежные вопросы