如何在jQuery ajax中添加新的ZF2'Zend \ Form \ Element

时间:2013-02-02 08:26:13

标签: zend-form zend-framework2 zend-form-select

我想在jQuery ajax中添加一个新的ZF2'Zend \ Form \ Element。但是当我使用Zend Form时,我不知道如何制作它。这是add.phtml文件。

<script type="text/javascript">
 $(document).ready(function(){
    $(".pid").change(function(){
    var id = $('.pid').val();
    var $_this = $(this);
     $.ajax({
            type:"POST",
            url:"<?php echo $this->url('Element/default',array('action'=>'change'));?>",
            data:"pid="+id,
            dataType:'json',
            async:false,
            success:function(data){
                if(data.response){
                   //here I want to add a new select  component after select conponent "pid" using like "$this->formRow($form->get('mid'))" or else .   
                }
            }
    });
  });
});
</script>

以下是html的剩余部分。

<?php
$title = 'add';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>

<?php
$form = $this->form;

$form->setAttribute('action', $this->url(
'Element/default',
array(
    'action'     => 'add'
 )
));
$form->prepare();

echo $this->form()->openTag($form); 
echo $this->formRow($form->get('pid'));
echo $this->formRow($form->get('name'));
echo $this->formRow($form->get('desc'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();

如何在jquery ajax中添加新的zend表单元素?感谢。

1 个答案:

答案 0 :(得分:0)

您有使用ajax接收数据的脚本,此脚本应接收view / html。您需要控制器/操作来呈现数据并作为响应返回。

use Zend\View\Model\JsonModel;    
//some controller
public function changeAction(){ // your requested action
    //1. get partial helper to rendering html;
    $partial = $this->getServiceLocator()->get('ViewHelperManager')->get('partial');
    $form = new Form();// your form
    //2. render html
    $html = $partial('path/to/your/file/phtml',['form'=>$form]);
    //3. return data as JSON because in your ajax configuration dataType: 'json'
    return new JsonModel([
        'html' => $html,
    ]);
}
你的js成功函数中的

应该是:

success:function(data){
    if(data.html){
         $_this.find('blockToAppend').append(data.html);
    }
}