jQuery 创建 HTML 按钮以运行 Python 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15166941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:32:11  来源:igfitidea点击:

Create HTML button to run Python Script

jqueryhtmlajaxdjangolighttpd

提问by user2125116

I am trying to create a button on a webpage quad_relay.html

我正在尝试在网页 quad_relay.html 上创建一个按钮

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.o$
<html xmlns="http://www.w3.org/1999/xhtml">
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
 <body>
   <h1>Quad Web Relay</h1>
   <div>Relay 1:
     <input type="button" value="Toggle" id="toggle1" />
   </div>
 </body>
</head>
</html>

When that button is clicked I want it to run a python script set_gpio.py

单击该按钮时,我希望它运行 python 脚本 set_gpio.py

def set_pins_high():
        fp = open("/sys/class/gpio/gpio"+pin+"/value","w")
        fp.write(str(1))
        fp.close()
def set_pins_low():
        fp1 = open("/sys/class/gpio/gpio"+pin+"/value","w")
        fp1.write(str(0))
        fp1.close()

for pin in pins:
        for x in range (0,2):
                set_pins_high()
                time.sleep(0.5)
                set_pins_low()
                time.sleep(0.5)

The webpage is located on a lighttpd server running Django. I have jQuery and AJAX installed, and I know they are the route that I need to take to accomplish this however everytime I try something it doesnt work.

该网页位于运行 Django 的 lighttpd 服务器上。我安装了 jQuery 和 AJAX,我知道它们是我需要采取的方法来实现这一点,但是每次我尝试一些东西时它都不起作用。

回答by Fernando Freitas Alves

you have to do some modifications:

你必须做一些修改:

In your HTML file:

在您的 HTML 文件中:

<div>Relay 1:
  <form action= '{% url my_view_name%}' method="POST">
      <input type="submit" value="Toggle" id="toggle1" />
  </form>
</div>

in urls.py

在 urls.py 中

url(r'whatever^$', 'core.views.my_view',name='my_view_name'),

In views.py:

在views.py中:

def my_view(request):
    if request.method == 'POST':
        import set_gpio
        #Do your stuff ,calling whatever you want from set_gpio.py

    return #Something, normally a HTTPResponse, using django