基于Ajax post请求呈现不同的Zend表单

时间:2013-01-27 02:27:22

标签: ajax zend-framework

我正在尝试使用Ajax post请求显示基于用户类型的不同表单。请求响应正常,但我不知道如何显示表单。例如,如果用户选择父级,则我希望显示父级表单,依此类推。我正在使用ZF 1.12。

public function init() {
    $contextSwitch = $this->_helper->getHelper('AjaxContext');
    $contextSwitch =$this->_helper->contextSwitch();
    $contextSwitch->addActionContext('index', 'json')
    ->setAutoJsonSerialization(false)
    ->initContext();
}

public function indexAction() {
    $this->view->user = $this->_userModel->loadUser($userId);
    //if($this->_request->isXmlHttpRequest()) {
        //$this->_helper->layout->disableLayout();
        //$this->_helper->viewRenderer->setNoRender(true);
    if ($this->getRequest()->isPost()){
        $type = $_POST['type'];
        $this->view->userForm = $this->getUserForm($type)->populate(
            $this->view->user
        );
    }
}

这就是我在客户端所拥有的。在成功部分我需要写什么?

<script type="text/javascript"> 
  $(document).ready(function(){
    $('#userType').on('change', function(){
      var type = $(this).val();
      select(type);
    });
  });

  function select(type) {
    $.ajax({
        type: "POST",
        url: "admin/index/",
        //Context: document.body,
        data: {'type':type},
        data: 'format=json',
        //dataType: "html",
        success: function(data){
         // what to do here?
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {}
    });
}
</script>
<form id="type" name="type" method="post" action="admin/index">
  <select name='userType' id='userType' size='30'>
    <option>admin</option>
    <option>parent</option>
    <option>teacher</option>
  </select>
</form>
<div id="show">
  <?php //echo $this->userForm;?>
</div>

1 个答案:

答案 0 :(得分:1)

如果您的ajax请求表单返回Zend_Form中的HTML,您只需在#show div中编写HTML。

在您看来,您需要这样做:

echo $this->userForm;

这样,在将响应发送到HTML页面之前,所有必需的HTML都将写在服务器端。在HTML页面中,您只需使用方法$('#show').html(data)在正确的位置编写响应。您还必须确保每个表单在呈现时都有正确的操作。

另一种选择是在加载时将所有三个表单隐藏在页面中(通过Javascript)并基于select(Generated with JS),显示正确的表单。这样您就不必从外部源加载数据,如果有人禁用JS,他仍然可以使用该应用程序。另一方面,此方法将使每个页面加载大约1/2 a KB的数据。

相关问题