使用ajax单击按钮即可运行php脚本 [英] Use ajax to run php script with button click
问题描述
我是一名业余爱好者,对html,javascript,php的了解有限.我将Raspberry Pi微型计算机设置为Web服务器.首先,我想打开一个通过网页上的按钮连接到Pi的LED.我有以下有效的代码(html文件的名称为min.php):
I am a hobbyist with limited knowledge of html, javascript, php. I set up a Raspberry Pi microcomputer as a Web server. As a starting point I want to turn on a LED that is connected to the Pi with a button on a Web page. I have the following code that works (name of html file is 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代码更改如下:
Now I want to rewrite the code with an ajax function so that the page does not reload when the button is clicked and here I have problems. I looked at a lot of the posted examples but I just can't get over the hump. I changed the html code as follows:
<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文件存储在同一目录中:
The LED_On.php file has the following code and is stored in the same directory as the html file:
<?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.感谢您的帮助.
Clicking the button does not turn on the LED. Any help is appreciated.
推荐答案
检查代码
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"><?script>
<?script>
应该更改为</script>
这篇关于使用ajax单击按钮即可运行php脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!