我是Zend Framework的新手。我正在尝试使用 JSON 显示数据库中的数据。我对数据进行了编码并将其传递给JQuery。但无法从数据库中检索值。数据显示为"未定义"。我的控制器功能如下:
public function displayAction()
{
$data1 = array();
$request = $this->getRequest();
$response = $this->getResponse();
if ($request->isPost()) {
$response->setContent('Zend'Json'Json::encode(array('data' => $this-> getStickyNotesTable() -> fetchAll())));
}
return $response;
}
My FetchAll() 是:
public function fetchAll() {
$resultSet = $this->select(function (Select $select) {
$select->order('created ASC');
});
$entities = array();
foreach ($resultSet as $row) {
$entity = new Entity'StickyNote();
$entity->setId($row->id)
->setNote($row->note)
->setCreated($row->created);
$entities[] = $entity;
}
return $entities;
}
JQuery 功能:
function getUserList(element) {
$('#indicator').show();
$.post('stickynotes/display',
function(data, textStatus) {
renderUserList(data);
$('#indicator').hide();
},
"json"
);
}
function renderUserList(jsonData) {
var table = '<table width="600" cellpadding="5" class="table table-hover table-bordered"><thead><tr><th scope="col">Note</th></tr></thead><tbody>';
$.each(jsonData, function(index, data){
table += '<tr>';
table += '<td class="edit" field="note" user_id="'+data.id+'">'+data.note+'</td>';
table += '<td><a href="javascript:void(0);" user_id="'+data.id+'" class="delete_confirm btn btn-danger"><i class="icon-remove icon-white"></i></a></td>';
table += '</tr>';
});
table += '</tbody></table>';
$('div#content').html(table);
}
我用Firebug测试了它。它显示
{"data":[{},{},{},{},{},{},{},{},{},{},{},{},{}]}
作为响应。任何人请帮助我。谢谢。
问题出在您的 fetchAll 方法上。尝试使用此更新版本:
public function fetchAll() {
$resultSet = $this->select(function (Select $select) {
$select->order('created ASC');
});
$entities = array();
foreach ($resultSet as $row) {
$entity = array(
"id" => $row->id,
"note" => $row->note,
"created" => $row->created
);
$entities[] = $entity;
}
return $entities;
}
您需要
配置module.config.php
并在template_map中添加策略。
'strategies' => array(
'ViewJsonStrategy',
),
以返回 jsonModel。
如果你想在你的控制器中使用一个jsonModel,你需要像这样调用它:
$json = new JsonModel(array(
'param' => 'foobar',
'success' => true,
));
return $json;