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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?