简体   繁体   中英

php variable issue in javascript

i want to generate loop of javascript in php which give me syntax error.here is what i want

var d1 = [
          [(new Date("01/06/2013")). getTime(),4],
          [(new Date("01/07/2013")). getTime(),0],
         ];

i want to make it dynamic from db.here is what i tried

var d1 = [
<?php
    while($rw = $oAppl->row($res))
    {
        $php_var = $rw['list_date_rent'];
        $php_var2 = $rw['rntval'];
?>            
    var php_var = "<?php echo $php_var; ?>";
    var php_var2 = "<?php echo $php_var2; ?>";
    [(new Date("+'"php_var"'+")). getTime(),php_var2],
<?php
    }
?>
];

Why are you using the javascript variables ?

var d1 = [
<?php while($rw = $oAppl->row($res)) { ?>
  [(new Date("<?php echo $rw['list_date_rent']; ?>")). getTime(),<?php echo $rw['rntval']; ?>],
<?php } ?>
     ];

You do NOT want a trailing comma and you need to either echo the complete thing or split your echo into two - this is perhaps more readable

var d1 = [];
  <?php
    $first = true;
    while($rw = $oAppl->row($res)) {     
      if (!$first) echo ","; else $first=false; ?>
      d1.push([ 
        new Date("<?php echo $rw['list_date_rent']; ?>").getTime(),
        <?php echo $rw['rntval']?>
      ]);
   <?php } ?>  

Why not just build the array in PHP and then use json_encode to output it into javascript?

$results = array();
while ($rw = $oAppl->row($res)) {
    $results[] = array(
        'new Date("' . $rw['list_date_rent'] , '").getTime()',
        $rw['rntval']
    );
}

?>
var d1 = <?php echo json_encode($results); ?>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM