![](/img/trans.png)
[英]How do I send a python variable over to javascript? The python is a cgi script?
[英]How do I call a python function from a cgi script with javascript?
我還想在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的新手,對此我將不勝感激。 另外,如果您知道我可以做的更好,請告訴我。 謝謝!
因此,經過長時間的嘗試和錯誤,並等待着從未有過的答案,我想出了自己的方法,因此我想我可以幫助需要此功能的人,我可以使用python cgi腳本發送請求像這樣的javascript:
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函數進行調試對我有幫助。 希望這可以幫助某人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.