我想根据 mysql 数据库中表内的值(该表只有一行)显示 onload 一个(某种)切换按钮,并且当我单击它时,我想更改同表从 0 到 1 或相反。我已经看到很多关于相关问题的答案,但似乎没有一个对我有用。非常需要一些帮助。多谢!
这是我的 PHP 代码:
<?php
include 'db_ecoheating.php';
mysql_connect($dbhost,$dbuser,$dbpass)
or die ("Unable to connect to database");
mysql_select_db($dbname)
or die ("Unable to select database");
$sql = "SELECT coil1 from coils ";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$coil1 = $row['coil1'];
}
$arr = array(
'value1'=> $coil1,
);
echo json_encode($arr);
?>
还有我在 js 中的函数(包括 jquery):
function buttonFunctions(){
var x1=document.getElementById("coil1");
var value = $.ajax({
type: "GET",
url: "coils.php",
data: query,
dataType: "json"
success: function(data){
console.log(data.value1);
}
});
if(value=='0') coil1.src = "Button2.png";
else if(value=='1') coil1.src = "Button1.png";
//coil1.src="Button1.png";
}
还有我的图片(作为按钮使用):
<input type="image" onclick="saveData()" id="coil1"/>
最佳答案
虽然使用 JS 的想法没问题,但您可以使用纯 PHP 和 HTML/CSS 来实现。 我还建议您开始使用 mysqli/PDO。
/*CSS */
.button0 {background-image: url("Button1.png");}
.button1 {background-image: url("Button2.png");}
然后,要显示您的按钮,请使用以下 PHP 代码
<?php
include 'db_ecoheating.php';
mysql_connect($dbhost,$dbuser,$dbpass) or die ("Unable to connect to database");
mysql_select_db($dbname) or die ("Unable to select database");
$sql = "SELECT * FROM coils";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$value = $row['coil1']; ?>
<input class="button<?php echo $value; ?>" type="image" onclick="saveData()" id="coil1"/>
<?php } ?>
关于javascript - 如何根据 mysql 数据库中的值在 html 中显示(加载)开/关按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36716606/