dsbo44836129 2013-11-20 07:11
浏览 35
已采纳

最佳练习javascript数据格式化[关闭]

I am fetching a list of users from the database table :

userid username created

1       xyz      1384875794

Where created is the UNIX time [using PHP time()] at which the user was created.

But in the browser while printing these users , i will be converting the php time into a readable format [eg. Nov 19 2013] using javascript .

Here comes my question :

Suppose if the javascript function format_time(time) converts the time into readable format .

Which of the following two ways is preferred

First way :

Use javascript inline like this

<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>   

Here the format_time() will use document.write() to print the formatted time.

Second way :

Use javascript after DOM load

  1. Get $users array from DB using ajax
  2. Loop through the array and do innerHTML

I can even remove above ajax request by converting the php variable $users to a javascript by JSON encode/decode and repeat the above second step.

  • 写回答

1条回答 默认 最新

  • douyan7916 2013-11-20 07:23
    关注

    In this case I suggest you process the issue format of time in php, then output the processed result:

    <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> 
    

    If you just want to output the $users object then use it in javascript, you can do it like below:

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

    Then you can access users in javascript.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行