隐藏基于PHP输出的图像

时间:2014-05-13 08:05:45

标签: php html

所以我想创建一个以基于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()函数,我已经完成了。我有2个文件(lightbulb_1和lightbulb_0)。如果getLampState()返回1,我想显示lightbulb_1,反之亦然。

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

使用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脚本中简单地&#34; echo&#34;无论你想要什么回归。

如果您对包含JQuery感兴趣,只需在HTML的开头包含以下内容:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

答案 1 :(得分:0)

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;

}
?>

这有用吗?