将python cgi脚本的结果发送到HTML

2024-10-02 08:15:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在页面上有一个切换按钮'索引.html'. 当我点击它时,它会执行一个pythoncgi脚本来改变我的raspberry上某个东西的状态。在

为此,我要这样做:

HTML:

<form id="tgleq"  method="POST" action="/cgi-bin/remote.py" target="python_result">
<input id="toggle-eq" type="checkbox" data-toggle="toggle" name="toggle-eq" value="">

<script>
$(function() {
  $('#toggle-eq').change(function() {
    tgl_state = $('#toggle-eq').prop("checked")
    var toggle = document.getElementById("toggle-eq");
    toggle.value = tgl_state;
    document.getElementById("tgleq").submit();
  })
})
</script>

CGI:

^{pr2}$

然后我对arg1执行我想做的事情。在

现在,我想要的是,当您打开web界面页面时,获取raspberry组件的状态,以便在正确的位置初始化切换。在

为此,我在页面加载时发送一个表单,启动一个查看组件状态的脚本。但是我怎样才能在html中恢复它呢?在

我尝试了urllib和httplib2,但没有对我有用。。。有什么建议吗?在

谢谢


Tags: 脚本idvalue状态htmlscriptfunction页面
1条回答
网友
1楼 · 发布于 2024-10-02 08:15:41

如果我正确理解您的问题,您希望在网页上显示可切换组件的当前状态。 目前看起来你有一个纯HTML页面和一个CGI页面,所以我认为你有多种选择,其中之一就是将HTML和CGI组合成一个页面。在

下面的代码就是这种想法的一个例子,可能无法正常工作,因此不是一个复制/粘贴解决方案。在

#!/usr/bin/env python
import cgi
import cgitb

cgitb.enable()
print "Content-type: text/html\n\n"
print
active="""
<form id="tgleq"  method="POST" action="/cgi-bin/remote.py" target="python_result">
<input id="toggle-eq" type="checkbox" data-toggle="toggle" name="toggle-eq" value="">
"""
inactive="""
<form id="tgleq"  method="POST" action="/cgi-bin/remote.py" target="python_result">
<input id="toggle-eq" type="checkbox" data-toggle="toggle" name="toggle-eq" value="checked">
"""
generic = """
<script>
$(function() {
  $('#toggle-eq').change(function() {
    tgl_state = $('#toggle-eq').prop("checked")
    var toggle = document.getElementById("toggle-eq");
    toggle.value = tgl_state;
    document.getElementById("tgleq").submit();
  })
})
</script>
"""

def set_state(option):
    if (option==True):
        actual_state_Setting_here = 1 # <-magic happens here
    else:
        actual_state_Setting_here = 0 # <-magic happens here

def get_state():
    return actual_state_Setting_here # <- read actual value here

form = cgi.FieldStorage()
if ( form.getvalue('toggle-eq')=="checked" ):
    set_state(True)
else:
    set_state(False)

if ( get_state()==True ):
    print(active) #show as currently active
else:
    print(inactive) #show as currently inactive
print(generic) #show rest of the page

相关问题 更多 >

    热门问题