【发布时间】:2022-11-17 08:43:42
【问题描述】:
我正在尝试解决一个问题,我想在其中使用不使用表单字段本身的编程形式将数据发送到后端 python cgi 脚本。但是,我不知道如何使用 python 接收该文本。有了我可以使用的表格
"form = cgi.FieldStorage()"。但是,目前,我正在尝试使用"XMLHttpRequest.send()" 发送数据,但我还是不知道如何从 python cgi 脚本中捕获这些数据。所以基本上在这里,我有两个问题。到目前为止,在下面的代码中,我尝试使用 JS 获取输入值并尝试创建 HTTPRequest 以发送到 python 脚本。但是输出导致错误被异常"Request Failed"捕获
#Update:我能够修复它。如果有人需要它。我会保留这个职位。
//This is the HTML file
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Login(Async)</title>
</head>
<body>
<h1> Please Login </h1>
<label for="userName"> User Name </label><br>
<input type="text" id="username" name="username" placeholder="User"><br>
<label for="userName"> Password </label><br>
<input type="password" id="pwd" name="pwd" placeholder="Password"><br><br>
<button type="button" onclick="callCheckPass()"> Login </button>
<p id="contentArea"> </p>
</body>
<script>
function callCheckPass(){
asyncRequest = new XMLHttpRequest();
try{
asyncRequest.addEventListener("readystatechange", stateChange, false);
asyncRequest.open("POST", "checkpass.py", true);
asyncRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
asyncRequest.send("username=" + document.getElementById("username").value + "&" + "pwd="+
+ document.getElementById("pwd").value);
}catch(exception){
alert("Request Failed !!!");
}
}
function stateChange(){
if(asyncRequest.readyState == 4 && asyncRequest.status == 200){
document.getElementById("contentArea").innerHTML = asyncRequest.responseText;
}
}
</script>
</html>
//This is the python script // I am not sure how to catch HTTPRequest in python.
#!C:\Program Files\Python311\python.exe
import cgi, cgitb
cgitb.enable()
#instance of Field Storage
data = cgi.FieldStorage()
#get data from fields.
username = data.getvalue('username')
print("Content-type: text/html\r\n\r\n")
print("<html>")
print("<head><title> Test </title> </head>")
print("<body> <h1> Input: %s </h1> </body>"%(username))
print("</html>")
【问题讨论】:
-
看起来你通过捕获客户端请求抛出的异常来掩盖应该是有价值的错误信息,但随后没有对异常做任何事情。与其显示
"Request Failed !!!",不如显示已捕获的异常中包含的消息怎么样?您知道请求是否正在向服务器发出吗?您是否查看过相关的日志文件(如果有)?我从来没有使用过 CGI,所以我什至不知道在故障排除方面该问些什么。我很好奇你为什么使用 CGI 而不是像 Flask 这样的东西。 -
你说“我不确定如何在 python 中捕获 HTTPRequest”。如果您正在编写 CGI 脚本,那么“捕获请求”应该由为您的 CGI 脚本提供服务的服务器在幕后完成。您是否有任何 CGI 代码正在运行……是否有任何运行的测试用例?或者,您是否有一些 CGI 代码但不知道如何托管它或它的实际工作原理?我想知道的是,如果您想首先使用 CGI。
-
问题是,我似乎无法从服务器端使用“cgi.FieldStorage()”获取数据。由于某种原因,通过 ajax 发送数据并没有发送数据。
-
#Update:输出错误已修复,但是输出没有显示我应该从输入字段接收的数据。
-
您如何托管您的 CGI 脚本?你能否更准确地描述你所看到的情况。所以你点击网页上的按钮,会发生什么?你说“输出没有显示”。这到底是什么意思?什么输出?您是否在服务器端看到任何行为?您可以提供的信息越多,信息越清晰,某人帮助您解决问题的机会就越大
标签: javascript python ajax