运行 PHP 单击图像时的脚本

Run PHP script when clicking on a image

所以我刚刚在邮件中收到了我的新 raspberry pi 并且已经试用了一段时间。
现在,我希望能够使用 PHP 代码打开 LED。
假设我得到了以下图像:
<img src="images/On.png">
我怎样才能让它在我单击该按钮时运行以下 PHP 代码而不转到其他页面?

system ( "gpio mode 7 out" );
system ( "gpio write 7 1" );

我已经使用按钮尝试了以下方法,效果很好:

<?       
if ($_POST['submit'])  
{ 
    system ( "gpio mode 7 out" );
    system ( "gpio write 7 1" );
} 
if ($_POST['submit2'])
{
    system ( "gpio mode 7 out" );
    system ( "gpio write 7 0" );
} ?>
<form method="post" action=""> 
<input type="Submit" name="submit" value="On">
<input type="Submit" name="submit2" value="Off">
</form>

但现在我想把它与图像一起使用,但同样的代码似乎不能那样工作。
提前致谢。

您可以使用 jQuery 的 $.ajax

只需给 img 一个 id,您就可以这样做:(示例)

$("img#light-on").click(function(){
  $.ajax({
    type: "POST",
    url: "light-on.php",
    data: {lighton: "true"},
    success: function(){
      $("p.status").html("The light is on!");
    }
  });
});

然后您必须 运行 为 img#light-off 做同样的事情然后转到 light-off.php

您需要像这样加载 jQuery:

<script src="jquery-1.11.2.min.js"></script>

然后 运行 单独的代码 script:

<script>
  $(document).ready(function(){
    $("img#light-on").click(function(){
      $.ajax({
        type: "POST",
        url: "light-on.php",
        data: {lighton: "true"},
        success: function(){
          $("p.status").html("The light is on!");
        }
      });
    });
  });
</script>