【问题标题】:Use ajax to run php script with button click使用 ajax 通过单击按钮运行 php 脚本
【发布时间】:2016-08-24 05:29:05
【问题描述】:

我是一个业余爱好者,对 html、javascript、php 的了解有限。我设置了一台 Raspberry Pi 微型计算机作为 Web 服务器。作为起点,我想通过网页上的按钮打开连接到 Pi 的 LED。我有以下有效的代码(html 文件的名称是 min.php):

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>LED Control</title>
</head>
    <body>
    LED Control:
    <form method="get" action="min.php">
        <input type="submit" value="ON" name="on">
    </form>
    <?php
    $setmode7 = system("gpio mode 7 out");
    if(isset($_GET['on'])){
        $gpio_on = system("gpio write 7 1");
        echo "LED is on";
    }
    else {
        echo "LED is off";
    }
    ?>
    </body>
</html>

现在我想用 ajax 函数重写代码,以便在单击按钮时页面不会重新加载,这里我遇到了问题。我看了很多张贴的例子,但我就是无法克服困难。我修改了html代码如下:

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>LED Control</title>
</head>
<body>
<button type="button" onclick="LED_On()">LED On</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"><?script>
<script>
function LED_On(){
    $.ajax({
        url:"LED_On.php",
        type:"GET",
        data:"on"
    });
}
</script>
</body>
</html>

LED_On.php文件代码如下,与html文件存放在同一目录下:

<?php
if(isset($_GET['on'])){
     $setmode7 = system("gpio mode 7 out");
     $gpio_on = system("gpio write 7 1");
     echo "LED is on";
     }
     else {
        echo "LED is off";
    }
?>

单击按钮不会打开 LED。任何帮助表示赞赏。

【问题讨论】:

  • 是否做过任何基本的调试,比如检查 ajax 代码是否真的向服务器发送了 HTTP 请求?检查它是否调用了您的脚本?检查system() 调用是否有任何作用?
  • data:{on:"true"}
  • 可能是&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"&gt;&lt;?script&gt; 需要是&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"&gt;&lt;/script&gt;

标签: php ajax


【解决方案1】:

检查你的代码

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"><?script>

&lt;?script&gt; 应改为&lt;/script&gt;

【讨论】:

  • 就是这样。谢谢。
猜你喜欢
  • 2017-04-08
  • 1970-01-01
  • 2016-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多