最佳练习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.

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.