0

我正在尝试使用 Ajax 发布请求根据用户类型显示不同的表单。请求响应工作正常,但我不知道如何显示表单。例如,如果用户选择 parent,那么我希望显示父表单,依此类推。我正在使用 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>
4

1 回答 1

1

如果您的 ajax 请求表单从 Zend_Form 返回您的 HTML,您可以简单地在#showdiv 中编写 HTML。

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

echo $this->userForm;

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

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

于 2013-01-28T15:10:25.803 回答