最佳实践javascript数据格式化

时间:2013-11-20 07:11:32

标签: javascript php html ajax

我从数据库表中获取用户列表:

userid username created

1       xyz      1384875794

创建 的时间是[使用PHP time()]创建用户的UNIX时间。

但是在浏览器中打印这些用户时,我会将php时间转换为 可读格式[例如2013年11月19日]使用javascript。

我的问题出现了:

假设javascript函数format_time(time)将时间转换为可读格式。

首选以下两种方式中的哪一种

第一种方式:

像这样使用javascript内联

<table>
<?php foreach($users as $user) {
 <tr>
   <td> <?php echo $user['name']; ?> </td>
   <td> <script>format_time(<?php echo $user['created']; ?>)</script></td> 
 </tr>
<?php } ?>
</table>   

这里format_time()将使用document.write()来打印格式化的时间。

第二种方式:

在DOM加载后使用javascript

  1. 使用ajax
  2. 从DB获取$ users数组
  3. 遍历数组并执行innerHTML
  4. 我甚至可以通过转换php变量$ users来删除上面的ajax请求 通过JSON编码/解码到javascript并重复上面的第二步。

1 个答案:

答案 0 :(得分:1)

在这种情况下,我建议您在php处理时间的问题格式,然后输出处理结果:

<table>
<?php foreach($users as $user) {
 // format_time is a function to format time in php script
 $created = format_time($user['created']);?>
 <tr>
   <td> <?php echo $user['name']; ?> </td>
   <td> <script>format_time(<?php echo $created; ?>)</script></td> 
 </tr>
<?php } ?>
</table> 

如果你只想输出$ users对象然后在javascript中使用它,你可以像下面这样做:

<?php
$users = array(array('name' => 'srain'));
echo "<script type='text/javascript'>var users = " . json_encode($users) . ";</script>";
?>

然后您可以通过javascript访问用户。

相关问题