將PHP值透過Array來繼續,並將Array轉成json_encode餵給JavaScript變數即可
<!DOCTYPE html> <html> <head> <title></title> <meta charset="utf8"> </head> <body> <?php $db = new PDO('mysql:host=localhost;dbname=test', 'root', '123456789', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8';")); $array = array(); foreach ($db->query('SELECT * from school') as $value) { $array[] = $value; } echo json_encode($array); $db = null; ?> <script type="text/javascript"> var array = <?php echo json_encode($array)?>; var m_length = array.length; for(var index = 0; index < m_length; index++){ alert(array[index].number.toString()); } </script> </body> </html>
參考資料:
http://www.php.net/json_encode
http://stackoverflow.com/questions/18784178/php-array-to-javascript-array