如何用AJAX从非表单HTML字段向Python CGI发送并接收数据?
问题解决:通过XMLHttpRequest向Python CGI脚本发送数据
之前用表单提交数据时,后端Python CGI脚本可通过form = cgi.FieldStorage()获取数据,但改用XMLHttpRequest.send()编程式发送数据时,不清楚如何在CGI脚本中接收,且JS代码运行时触发了“Request Failed !!!”异常。已解决该问题,保留内容供他人参考。
HTML文件
<!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>
Python CGI脚本
#!C:\Program Files\Python311\python.exe import cgi, cgitb cgitb.enable() # FieldStorage实例 data = cgi.FieldStorage() # 获取字段数据 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>")
内容的提问来源于stack exchange,提问作者Mendax
相关产品推荐
相关产品推荐

