如何使用javascript从cgi脚本调用python函数?

2024-10-01 11:38:58 发布

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

我还想在javascript函数中使用XMLHttpRequest对象,从下拉列表(下面的代码中称为“Users”)中发送有关当前所选选项的信息,作为Python脚本中函数的参数,然后从该函数获取返回值并用它设置另一个列表(“下面代码中的Tasks”)I想这样做,这样我就可以用从Python函数中得到的返回值来更新“Tasks”中的信息,因为我不需要重新加载页面。如果你知道更好的方法来实现这一点,我会开放的想法。在

def main():
with open("Users.json", 'r') as data_file:
    usersDictionary = json.load(data_file)
Users=usersDictionary["Users"]
print "Content-Type: text/html"
print ""
print """
<html>
<head>
    <script>
      function setTaskList(){
          #Insert Javascript which will call python function here...
      }
        </script>
        <title>TestPage</title>
    </head>
    <body onload="setTaskList()">
        <form>"""
print """<select name="Users" onchange="setTaskList()">"""
for user in Users:
    if(not(len(user["Tasks"]["High"])==0 and len(user["Tasks"]["Med"])==0 and len(user["Tasks"]["Low"])==0)):
        print """<option value="{0}">{1}</option>""".format(user["UID"], user["name"])
print "</select>"
print """<select name="Tasks" disabled="disabled">"""
print "</select>"
print"""<input type="Submit" value="Add Task"/>
<button type="button">Delete Task</button>"""
print"""
        </form>
</body>
</html>"""

main()

对于下面的代码,我希望能够在单击submit时从输入框中获取数据,并将从输入框和单选按钮获得的信息发送到python函数进行处理,并将其作为JSON对象添加到JSON字典中,然后更新JSON文件,然后返回上一页(即上面代码所在的页面)(假设调用索引.py). 在

^{pr2}$

有谁能帮忙吗,我对这个CGI的东西很陌生,我会非常感激的。另外,如果你知道一个更好的为我做这件事,请让我知道。 谢谢!在


Tags: 对象函数代码name信息jsonlenhtml
1条回答
网友
1楼 · 发布于 2024-10-01 11:38:58

因此,经过长时间的反复试验,在等待一个从未出现的答案后,我自己想出了如何做到这一点,因此我想我可以帮助任何需要帮助的人,我可以使用javascript从python cgi脚本发送一个请求,如下所示:

print "Content-Type: text/html"
print ""
print """
<html>
<head>
    <script>
    function getTasks() { 
       //put more processing in the function as needed
       var xmlhttp;
       var parameters = "This must be a string which will be the parameters 
       you will receive in your python script";
       var scriptName = "pythonScript To CommunicateWith.py";
       //may be .cgi as well depending on how you are using it
       if (window.XMLHttpRequest) {
           xmlhttp = new XMLHttpRequest();
        } else {
             xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("POST", scriptName, true);
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                //retrieve a json response and parse it into userTasks
                usersTasks = JSON.parse(xmlhttp.responseText);
             }
        }
        xmlhttp.send(parameters);
     }
    </script>

在我的python脚本中,java脚本点击这里是如何获取参数并处理它们的:

^{pr2}$

使用Pycharm和python CGIHTTPServer函数进行调试对我有帮助。 希望这对其他人有帮助。在

相关问题 更多 >