【问题标题】:send data from html field(Not Form) using AJAX to python cgi使用 AJAX 从 html 字段(非表单)发送数据到 python cgi
【发布时间】: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


【解决方案1】:

所以基本上在 python 程序中你会从 asyncRequest.send() 接收数据,它是你的输入字段的组合,创建一个查询参数,它基本上是通过 asyncRequest.send("Query Param"); 发送的然后使用 JS 中使用的变量名你会在你的 python 中获得值脚本。

   <!DOCTYPE html>
    <html>
    <head>
        <meta charset='utf-8'>
        <title>Login(Async)</title>
    </head>
    <script>
            function callCheckPass(){
                var username = document.querySelector("#user").value;
                var pwd = document.querySelector("#pass").value;
    
                asyncRequest = new XMLHttpRequest();
                asyncRequest.addEventListener("readystatechange", eve=>{
                    if(asyncRequest.readyState == 4){
                        document.getElementById("contentArea").innerHTML = asyncRequest.responseText;
                    }
                });
                asyncRequest.open("POST", "../../cgi-bin/checkpass.cgi", true);
                asyncRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                asyncRequest.send("username=" + username + "&" + "pwd=" + pwd);
    
            }
        </script>
    <body>
        <h1> Please Login </h1>
        User Name<br>
        <input type="text" id="user" ><br>
        Password<br>
        <input type="password" id="pass" ><br><br>
        <button type="button" onclick="callCheckPass()"> Login </button>
        <p id="contentArea"> </p>
        
    </body>
        
    </html>

//Python script

#!/usr/bin/python //path to your python.exe

import cgi
import cgitb
import csv

cgitb.enable()


#instance of Field Storage
form = cgi.FieldStorage()

#get data from fields.
user = form.getvalue('username') // username -> the variable used from JS, which is essential to get value. For some reason this worked for me
pwd = form.getvalue("pwd")

print("Content-Type: text/html
")
print("<html>")
print("<head><title> Test </title> </head>")
print("<body> <h1>")
print(form) // data printed in your web application.
print("</h1> </body>")
print("</html>")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 2014-06-07
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多