在select tag(view)中显示json值zend framework 2

时间:2014-09-08 09:05:20

标签: jquery ajax json zend-framework2

我的模型:从数据库中获取数据

public function getAllProjectDomain() {


        $dbadapter = $this->adapter;
        $sql = new Sql($dbadapter);
        $select = $sql->select();
        $select->columns(array('cmain'));
   $select->from('projcat');

    $selectString = $sql->getSqlStringForSqlObject($select);
        $result = $dbadapter->query($selectString, $dbadapter::QUERY_MODE_EXECUTE);
            foreach ($result as $row) {
             $entity = array(
            "domain"      => $row->cmain
        );
        $entities[] = $entity;
        }

        return $entities;   

    }

我的控制员:

 public function domainAction()
        {
       if ($this->getRequest()->isPost()) {

            $service = $this->getServiceLocator()->get('UserService');
            $result = $service->getAllProjectDomain();
            //it will go to service and the method from table

            $mail = $result;
        }
         $results = new JsonModel(array(
        'mail' => $mail,    
        ));

        return $results;
    }

我的观点:

<div class="form-group"> 
        <label for="experience" class="col-lg-2 control-label">Relevant Experience </label>
        <div class="col-lg-3">
            <select class="form-control" id="experience" name="experience" title="Please select experience">
                 <option value="" selected="selected" >--Select--</option>
         <?php  foreach ($mail as $value) { ?>
  <option value="<?php echo $value ?>"> <?php echo $value ?> </option>
<?php } ?>

            </select>
        </div>
    </div>

我的jquery:

$(document).ready(function() {

$.post("<?php echo $this->url('checkcourse'); ?>", {},
    function(data) {

        if (data.mail)
        {
            document.getElementById('experience').value=data.mail;
        }
        else
        {
             alert('no data');
    }     
    }, "json");
});

这里我试图显示下拉选项。选项列表应来自数据库。现在我在jquery(视图文件)中获取json值,但我不知道如何使它在select标签中显示。

1 个答案:

答案 0 :(得分:0)

编辑视图:

> <div class="form-group"> 
    >         <label for="experience" class="col-lg-2 control-label">Relevant Experience </label>
    >         <div class="col-lg-3">
    >             <select class="form-control" id="experience" name="experience" title="Please select experience">
    >                  
    > 
    >             </select>
    >         </div>
    >     </div>

在jquery函数中添加:

$('<option value="">'+'Select Action...'+'</option>').appendTo('#experience');
               for (var i = 0; i < data.length; i++){

                   $('<option value="'+data[i]['mail']+'">'+data[i]['mail']+'</option>').appendTo('#experience');
                }

而不是json模型尝试返回一个json数组

$this->getResponse()->setContent(Json::encode($arrayOfData))