数据未从Python发送到JavaScript



这是我的Python文件

import random
from flask import Flask, render_template
from captcha.image import ImageCaptcha
from captcha.audio import AudioCaptcha
app = Flask(__name__)

@app.route('/')
def generateCaptcha():
return render_template('main.html')
@app.route('/getCaptcha', methods=['POST'])
def getCaptcha():
result_str_image = ''.join(
(random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') for i in range(5)))
image = ImageCaptcha(width=280, height=90)
imageData = image.generate(result_str_image)
image.write(result_str_image, result_str_image + '.png')
return result_str_image
if __name__ == "__main__":
app.run(debug=True)

还有我的HTML文件

<!DOCTYPE HTML>
<html>
<head>
<title> Example </title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<link rel="shortcut icon" href="#">
</head>
<body>
<h1> Captcha Example </h1>
<div id="Captcha"></div>
<label> Enter the text from Captcha above </label>
<input type="text" id="CaptchaInput">
<br> <br>
<input type="button" value="Enter" id="CaptchaSubmit">
<input type="button" value="Reset" id="CaptchaReset">
<input type="button" value="Audio" id="CaptchaAudio">
<script>
var captchaValue;
$.ajax({
type: "POST",
url: "/getCaptcha",
data: captchaValue,
contentType:"application/text; charset=utf-8", // Declare the type of the data we're sending. Without this, Flask will misinterpret it as some other kind of data.
success: function(data){
console.log(captchaValue);
}
});
</script>
</body>
</html>

然而,captchaValue总是未定义的,我在哪里搞砸了?这是我第一次尝试这个。我正在使用Github中的一段代码来提供帮助,但由于他们在做其他事情,我很困惑我在哪里搞砸了。

我在等

data: captchaValue

以更新captchaValue的值。

首先,您没有捕获输入中输入的值,因此请查看https://flask.palletsprojects.com/en/2.0.x/quickstart/特别阅读"请求对象"部分。基本上,您在Flask应用程序中输入的所有数据都可以使用request.form对象(这是一种只读dict(捕获。然而,在完成这项工作之前,您必须首先将所有输入包含在一个表单标记中,类似于以下内容:

<label> Enter the text from Captcha above </label>´
<form method="POST">
<input type="text" id="CaptchaInput">
...
</form>

请注意,您应该添加方法参数,使其尽可能以最简单的方式工作。

然后你必须在所有输入中添加一个名称参数,你可以使用与相同的id名称

<input type="text" id="CaptchaInput" name="CaptchaInput">

然后,在Python代码中,您现在可以调用request.form['CapchaInput'](不要忘记在顶部导入请求库!(来捕获Flask中的值。

根据您的Javascript代码,您从未从输入中读取过值,因此您必须执行以下操作:var captchaValue=document.getElementById("CaptchaInput"(.value;

最新更新