【问题标题】:Send the result of python cgi script to HTML将 python cgi 脚本的结果发送到 HTML
【发布时间】:2015-06-04 13:57:49
【问题描述】:

我在“index.html”页面上有一个切换按钮。当我点击它时,它会执行一个 python cgi 脚本来改变我树莓上某些东西的状态。

为此,我这样做:

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:

#!/usr/bin/env python

import cgi
import cgitb

cgitb.enable()

print "Content-type: text/html\n\n"
print

form=cgi.FieldStorage()
arg1 = form.getvalue('toggle-eq')

然后我用我的 arg1 做我想做的事。

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

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

我尝试了urllib 和 httplib2,但对我没有任何帮助...有什么建议吗?

谢谢

【问题讨论】:

  • 你为什么要使用这些?您需要充当服务器,而不是客户端。
  • 对不起,我没明白你的意思...应该充当服务器?

标签: javascript python html cgi


【解决方案1】:

如果我正确理解您的问题,您希望在网页上显示可切换组件的当前状态。 目前看起来你有一个纯 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

【讨论】:

  • 感谢您的回复。事实上,这可能是一个很好的方法。但是我担心我的网页代码将来需要稍微复杂一些,并且很难将其处理成 python 脚本。你认为相反的可能吗?
  • 这是一个快速且基本的示例,您可以更清晰地构建所有内容,使其易于维护。如果您用任何其他语言编写它,您将遇到同样的问题。 Python 紧凑而干净,因此非常适合执行此操作。构建一些用于切换内容的基本脚本,将它们作为 REST 服务,其余的可以是纯 HTML 与 javascripts 的结合。
猜你喜欢
  • 1970-01-01
  • 2019-11-09
  • 2015-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-12
  • 2020-05-31
相关资源
最近更新 更多