如何在Zend Framework 2中使用ajax和json编码

时间:2015-03-25 03:54:33

标签: php jquery ajax json zend-framework2

我使用jquery尝试了一个简单的ajax aplication,错误是每个dataobject都为null。谁能帮我 ? 这是我的代码:

protected $mysqlAdapter;
protected $studentid;
protected $fullname;
protected $birthdate;
protected $placebirth;
protected $gender;
protected $id_religion;
protected $nm_religion;
protected $stdaddr;
protected $stdphone;
protected $stdcellular;
protected $stdemail;

public function indexAction()
{
    $request = $this->getRequest();
    $response = $this->getResponse();

    $nm_pd = $this->request->getPost('nm_pd');
    $tgl_lahir = $this->request->getPost('tgl_lahir');
    $id_agama = $this->request->getPost('id_agama');
    $nm_agama = $this->request->getPost('nm_agama');

    $dbAdapter = $this->getMysqlAdapter();
    $sql = new Sql($dbAdapter);
    $all = $sql->select();
    $all->from('v_datadetail_feeder');
    $all->where(array('studentid' => 11509002));
    $statement = $sql->prepareStatementForSqlObject($all);
    $result = $statement->execute();

    foreach ($result as $rs) {
        $studentid = $this->$rs['studentid'];
        $fullname = $this->$rs['fullname'];
        $birthdate = $this->$rs['birthdate'];
        $placebirth = $this->$rs['placebirth'];
        $gender = $this->$rs['gender'];
        $id_religion = $id_agama;
        $nm_religion = $nm_agama;
        $stdaddr = $this->$rs['stdaddr'];
        $stdphone = $this->$rs['stdphone'];
        $stdcellular = $this->$rs['stdcellular'];
        $stdemail = $this->$rs['stdemail'];
        $data = array('fullname'=>$fullname,
                      'studentid'=>$studentid,
                      'birthdate'=>$birthdate,
                      'placebirth'=>$placebirth,
                      'gender'=>$gender,
                      'id_agama'=>$id_religion,
                      'nm_agama'=>$nm_religion,
                      'stdaddr'=>$stdaddr,
                      'stdphone'=>$stdphone,
                      'stdcellular'=>$stdcellular,
                      'stdemail'=>$stdemail,
                      );
        $response->setContent(Json::encode($data));         
    }
    return $response;
}

结果:     {"全名":空," studentid":空,"出生日期":空," placebirth":空,"性别& #34;:空," id_agama":空," nm_agama":空," stdaddr":空," stdphone":空, " stdcellular":空," stdemail":空}

enter image description here

1 个答案:

答案 0 :(得分:3)

你必须使用ZF2 JsonModel(),在module.config.php文件中启用JsonStrategy

'view_manager' => array (
        'strategies' => array (
            'ViewJsonStrategy' 
        ) 
),

并在控制器中使用它:

$view = new JsonModel($jsonArray);
$view->setTerminal(true); // to disable layout
return $view;