【发布时间】:2017-03-31 07:21:03
【问题描述】:
当我触发我的 JavaScript 代码打开一个模式时,会发送一个 AJAX 调用来检索 JSON 格式的数据。然后我使用 JSON 响应来填充我的模式。
触发 JavaScript 的链接是这样的:
<?= $this->Html->link(__('View'), ['action' => 'popup', $session->id], ['class' => 'view', 'data-id' => $session->id]) ?>
这是一个来自于 CakePHP 3 视图的表格的动作。 $session->id 是根据点击链接的哪一行数据来决定的。 Popup 是一个空的 CakePHP 3 函数,它只是促进 JavaScript 工作和模式打开。
触发modal的JavaScript如下:
<script type="text/javascript">
$(function () {
$('.view').click(function (ev) {
ev.preventDefault();
var sessionId = $(this).attr('data-id');
$('#viewModal').modal('show');
$.ajax({
url:"localhost/project/sessions/details/"+sessionId+".json",
type:'POST',
success:function(res) {
if(res) {
document.getElementById("prdatestart").innerHTML = res.date_start;
document.getElementById("prstarttime").innerHTML = res.starttime;
}
}
});
});
});
</script>
我的 CakePHP 3 SessionsController 中的 details 函数是这样的,它检索之前获得的 $session->id 的相关数据:
public function details($id = null)
{
$details = $this->Sessions->get($id);
$this->set(array(
'output' => $details,
'_serialize' => 'output',
'_jsonp' => true
));
}
这是我的完整模态,然后打开:
<!-- Modal -->
<div class="modal fade" id="viewModal" tabindex="-1" role="dialog" aria-labelledby="viewModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="modal-title" id="viewModalLabel">Session Details</h3>
<br>
<table class="vertical table col-sm-2">
<tr>
<th>Starting Date:</th>
<td id="prdatestart"></td>
</tr>
<tr">
<th>Starting Time:</th>
<td id="prstarttime"></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close
</button>
</div>
</div>
</div>
</div>
但是,我的日期和时间是这种格式:
- 日期:2017-05-12T00:00:00+00:00
- 时间:2017-03-31T00:14:00+11:00
对于日期响应,我只需要日期,并格式化为 D/M/Y 格式。对于时间响应,我只需要时间,格式为 12 小时 hh:mm AM/PM 格式。 (我不需要最后的时区信息,因为在首次提交数据时已将其考虑在内)。
【问题讨论】:
-
您应该向我们提供负责返回日期的代码,您可以在这里进行格式化
-
@lonut:我尝试将 .moment().format('l') 添加到我的 json 响应中(例如 res.date_start,但它不起作用 - 我在控制台:
Uncaught TypeError: res.date_start.moment is not a function -
@Jaay 我已经包含了用于模态的 JavaScript 和现在检索数据的 CakePHP 3 函数。
标签: javascript json date time cakephp-3.0