基于PHP输出隐藏图像


Hiding images based on PHP output

所以我想创建一个图像,该图像在基于PHP函数的状态下启动,当单击时会更改状态。

我还没有找到任何方法将PHP中的函数的返回值转换为HTML。如果我能做到这一点,我的问题就解决了。

<?php
if(isset($_GET['button1'])){toggle();}
function toggle()
{
$filename = "brightness";
$otherDirectory="/sys/class/leds/led0/";
$f = fopen($otherDirectory . $filename,"r"); 
$value = fgets($f);
$newvalue = 1;
fclose($f);
if ((int)$value == 1) {
   $newvalue = 0;
}
if ((int)$value == 0) {
   $newvalue = 1;
}
    $f = fopen($otherDirectory . $filename,"w+"); 
fwrite($f, $newvalue);
fclose($f);
}
function getLampState(){
$filename = "brightness";
$otherDirectory="/sys/class/leds/led0/";
$f = fopen($otherDirectory . $filename,"r"); 
$value = fgets($f);
return $value;
}
?>
<html><body>
<img src="lightbulb_1.png" onClick='location.href="?button1"'/>
</body></html>

不要介意toggle((函数,我已经完成了。我有两个文件(lightbulb_1和lightbulb_0(。如果getLampState((返回1,则我希望显示lightbulb_1,反之亦然。

有什么建议吗?

使用JQuery。。。

$.ajax( {
    type: "GET",
    url: "phpScript.php",
    success:function(data){
    if(data==0)
        $("#imgTagId").attr("src","lightbulb1.png");
    else
        $("#imgTagId").attr("src","lightbulb2.png");
    }
});

在php脚本中,只需"echo"您希望返回的任何内容。

如果您对包含JQuery感兴趣,只需在HTML的头部任意位置包含以下内容:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
index.html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
function doThings(){
    $.ajax( {
    type: "GET",
    url: "script.php",
    success:function(data){
    //here whatever the script echos is inside "data"
    if(data==0)
        $("#imgId").attr("src","lightbulb_0.png"); //use # to select elements by id
    else
        $("#imgId").attr("src","lightbulb_1.png");
    }
    });
}
</script>
</head>
<body>
<!-- don't begin id's with numbers -->
<img id="imgId" src="lightbulb_0.png" onClick='doThings();'/>
</body>
</html>
script.php
<?php
//if(isset($_GET['button1'])){toggle();}
toggle();
function toggle()
{
        $filename = "brightness";
        $otherDirectory="/sys/class/leds/led0/";
        $f = fopen($otherDirectory . $filename,"r");
        $value = fgets($f);
        $newvalue = 1;
        fclose($f);
        if ((int)$value == 1) {
           $newvalue = 0;
        }
        if ((int)$value == 0) {
           $newvalue = 1;
        }
        $f = fopen($otherDirectory . $filename,"w+");
        fwrite($f, $newvalue);
        fclose($f);
        //this is what the html gets back (inside "data")
        echo $newvalue;
}
//what's this function?
function getLampState(){
        $filename = "brightness";
        $otherDirectory="/sys/class/leds/led0/";
        $f = fopen($otherDirectory . $filename,"r");
        $value = fgets($f);
        $filename = "lightbulb_";
        $fileending = ".png";
        echo $value;
}
?>

这行得通吗?