我正在使用zf2。我想通過使用ajax調用來加載我的第二個下拉列表。我嘗試了下面的代碼。我可以得到硬編碼的值。但我不知道如何將數據庫值添加到數組中並使用ajax將該值加載到下拉列表中。如何使用zf2做ajax + json?
阿賈克斯PHTML:
<script type="text/javascript">
$(document).ready(function() {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL :/name of the controller for the site/name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
//code to load data to the dropdown
},
error:function(){alert("Failure!!");}
});
});
});
</script>
控制器動作:
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable()->getkeyproject($key);
$projectid = $data->id;
$projectusers[] = $this->getRoleTable()->fetchRoles($projectid);
// eturn a Json object containing the data
$result = new JsonModel (array (
'projectusers' => $projectusers
));
return $result;
}
DB查詢:
public function fetchRoles($id) {
$resultSet = $this->tableGateway->select (array (
'projectid' => $id
));
return $resultSet;
}