使用jQuery與PHP抓取SQL查詢的整個表格資料(陣列資料)
這篇文章係協助專題生後整理產生。
JavaScript/HTML端
<script type="text/javascript"> tableBody = $("table tbody") $.post('b1.php', function(data) { //從後端傳入資料庫查詢的資料陣列 var result = $.parseJSON(data); //以json格式挖出data陣列裏的資料 $.each( result, function( key, value ) { //把陣列裏的資料一筆一筆… var str = "<tr><td>" + value['tabletime'] + "</td>" + "<td>" + value['detail'] + "</td>" + "<td>" + value['oktime'] + "</td>" + "<td><button type='button' class='de' data-detail='" + value['detail'] + "' data-tabletime='" + value['tabletime'] + "' id='ID' onclick='setFinished(this)'>完成</button></td></tr>"; tableBody.append(str); }); // console.log($('.bell_table').html()); }); function setFinished(elm){ // console.log($(this).data("detail")); // console.log($(this).data("tabletime")); console.log(elm.dataset.detail); //onclick='setFinished(this), this, elm參考月曆程式裏的dayClicked函式 console.log(elm.dataset.tabletime); } </script>PHP端 (只處理後端資料庫的溝通)
$result_array = array(); // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM `bell`"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { array_push($result_array, $row); //將資料一筆一筆推入資料陣列 } echo json_encode($result_array); } else { echo "0 results"; } $conn->close();