我想将一些数据从视图传递到我的控制器并从中创建CSV
文件。我已在view
:
Button
:
<a class="btn btn-primary" href="#" id="save-csv">Save to CSV</a>
其余观点:
<script type="text/javascript">
var oUrl = '<?= $this->url('application/infraplk', array()); ?>';
var projects = JSON.stringify(<?php echo json_encode($this->projects) ?>);
var podmiot = JSON.stringify(<?php echo json_encode($this->podmiot) ?>);
$('#save-csv').on('click', function () {
var podmiotCSV = $('#type-select-Podmiot').val();
var projektCSV = $('#type-select-Projekt').val();
var typCSV = $('#type-select-Typ').val();
var statusCSV = $('#type-select-Status').val();
var errorsCSV = $('#type-select-Błędy').val();
var data = [];
if (podmiotCSV)
data.push(podmiotCSV);
if (projektCSV)
data.push(projektCSV);
if (typCSV)
data.push(typCSV);
if (statusCSV)
data.push(statusCSV);
if (errorsCSV)
data.push(errorsCSV);
//alert(data.length);
$.ajax({
type: "POST",
url: 'save-csv-file',
data: data
});
});
</script>
这是我的模特:
<?php
public function getValueToSaveCsv(array $data) {
//FOR EXAMPLE
print_r($data[0]);
}
?>
我的控制员:
<?php
public function saveCsvFileAction(array $data) {
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=infraplk.csv");
$data = $_POST;
$model = new \Application\Model\InfraPlk($this->getDbCbkAdapter());
$rows = $model->getValueToSaveCsv($data);
$fp = fopen("php://output", 'w');
fputcsv($fp, array_keys(get_object_vars($rows[0])));
foreach ($rows as $row) {
fputcsv($fp, get_object_vars($row));
}
fclose($fp);
$result = new ViewModel(array(
));
return $result->setTerminal(true);
}
?>
这是我第一次使用AJAX。而且真的不知道该怎么做。有人可以帮忙吗?
答案 0 :(得分:0)
您可以尝试:
$.ajax({
type:"POST",
url:'save-csv-file',
data: {data: data},
success: function(response){
//do success action here
}
});