我對PHP很陌生並且在用戶界面上工作。 這是一個個人斷路器項目,其中瓦數和斷路器狀態(開/關)被髮送到數據庫。PHP/AJAX:自動化的MySQL查詢來管理按鈕類
我現在正在嘗試的是爲接口製作一個實時狀態按鈕。實質上,我希望按鈕類/背景顏色根據數據庫中的狀態行進行更改。 (狀態= 0 - >紅色狀態按鈕,狀態= 1 - >綠色狀態按鈕)。
我需要幫助的是每2-3秒自動查詢狀態值的數據庫。我知道如何查詢我想使用mysql/php讀取的值以及如何使用JavaScript函數切換按鈕類/背景顏色。
我應該使用AJAX進行自動化嗎?
這裏是我擺弄模塊:JSFIDDLE
下面是最近來源:
<!DOCTYPE html>
<html>
<head>
<script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(this).toggleClass("off");
});
});
</script>
<style>
div{
float: left;
color:#fff;
font-size:40px;
}
h2{
text-align: center;
}
.wrapper{
position: absolute;
top: 25%;
left: 10%;
margin-right: -50%;
transform: translate(-50%, -50%);
}
.one{
width: 125px;
height:100px;
}
.two{
width: 120px;
height:75px;
background:darkblue;
}
.three{
width:120px;
height:75px;
background:blue;
}
.button{
background-color: #4CAF50; /* Green */
border: 1px solid green;
color: white;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
float: left;
position: relative;
left: 15%;
}
.button2{
background-color: #4CAF50; /* Green */
border: 1px solid green;
color: white;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
float: left;
position: relative;
left: 15%;
}
.off {
background: red;
}
.button:hover {
background-color: #3e8e41;
}
.button2:hover {
background-color: #3e8e41;
}
</head>
</style>
<?php
$query ="SELECT status FROM ICBP.radio3 ORDER BY time DESC LIMIT 1;";
$result = mysql_query($query);
$status = mysql_fetch_row($result);
if($status = 0){
echo "off";
}
else if ($status = 1) {
echo "on";
}
?>
<body>
<h2>ICBP Dashboard</h2>
<div class="wrapper">
<div class="one">
<div class="two">
<a href="index3.php"><button class="button">Breaker 1</button></a>
<button class="button2">Status</button>
</div>
<div class="three">
<a href="index3.php"><button class="button">Breaker 2</button></a>
<button class="button2">Status</button>
</div>
</div>
<div class="one">
<div class="two">
<a href="index3.php"><button class="button">Breaker 3</button></a>
<button class="<?php echo $status ?>">Status</button>
</div>
<div class="three">
<a href="index3.php"><button class="button">Breaker 4</button></a>
</div>
</div>
</div>
</body>
</html>
關於我的做法任何指導是非常讚賞。
謝謝!
所以整個過程是這樣的:AJAX請求 - > php查詢 - >根據條件輸出字符串。你會澄清,如果我在HTML體內調用php腳本的正確軌道上?謝謝。 – giri
@giri請檢查我編輯的答案 - 這是整個應用程序的工作框架。你現在需要做的是堅持所需的邏輯到PHP腳本,你應該做的:) –