【问题标题】:How do I call a python function from a cgi script with javascript?如何使用 javascript 从 cgi 脚本调用 python 函数?
【发布时间】:2018-08-04 04:48:18
【问题描述】:

我还想在 javascript 函数中使用 XMLHttpRequest 对象从下拉列表(在下面的代码中称为“用户”)中发送有关当前选定选项的信息,作为我 Python 脚本中函数的参数,然后从该函数获取返回值并使用它来设置另一个列表(下面代码中的“任务”)我想这样做,以便我可以使用作为返回的数据更新“任务”中的信息Python 函数的值我这样做是因为我需要页面不必重新加载。如果您知道更好的实现方式,我会接受想法。

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()

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

print "Content-Type: text/html"
print ""
print"""<html>
<head>
    <title>Title</title>
</head>
<body>
    <form  action = "/~theUser/cgi-bin/index.cgi" method = "POST">
        Task Name:   <input type = "text" name = "TaskName" 
placeholder="Task name" />  <br />
        Task Description:    <input type = "text" name = "TaskDescription" 
placeholder="task description" /> <br />
        User ID:    <input type = "text" name = "UID" placeholder="User Id" 
/> <br />
        Priority <br/>
        <input type="radio" name="gender" value="High"> High<br>
        <input type="radio" name="gender" value="Medium"> Medium<br>
        <input type="radio" name="gender" value="Low"> Low<br>
        <input type = "submit" value = "Submit" />
    </form>
</body>
</html>"""

谁能帮忙,我对这个 CGI 东西真的很陌生,非常感谢。另外,如果您知道更好的方法让我这样做,请告诉我。 谢谢!

【问题讨论】:

    标签: javascript python html xmlhttprequest cgi


    【解决方案1】:

    所以经过长时间的反复试验,并等待一个从未出现的答案,我自己想出了如何做到这一点,所以我想我可以帮助任何需要这个的人,我能够从我的 python 发送请求像这样使用 javascript 的 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>
    

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

    #!usr/bin/python
    import sys
    import json
    
    args=sys.stdin.readlines() #args comes in as a list with one item in it 
    which is the parameter that you sent in from javascript
    
    arguments=args[0]
    print "Content-Type: text/html"
    print ""
    
    def getTasks(userName):
        """This function will do some processing and get the required return 
        value"""
        taskList=[]
        #read JSON file and get the info.
        with open("Somefile.json", 'r') as data_file:
            usersDictionary = json.load(data_file)
        data_file.close()
        """...do some process ing of data here, which will set some data into 
        the list called taskList"""
        return taskList #Return a list of all the tasks for the user.
    
    print json.dumps(getTasks(arguments)) 
    """convert the json to a string and print it out. what you print out here 
    will be what you will get as a string in the .responseText of the 
    XMLHttpRequest 
    object"""
    

    在这里使用 Pycharm 和 python CGIHTTPServer 函数进行调试对我有帮助。 希望这对那里的人有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-03-10
      • 2021-12-11
      • 1970-01-01
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多