Flash 从 HTML 表单中获取单个值

1 投票
1 回答
47 浏览
提问于 2025-04-12 04:28

我有以下的 html 代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sell Weapons</title>
</head>
<body>
<form action="{{ url_for('predict')}}"method="post">
    <label for="comment1">evaluate first product</label><br>
    <input type="text" id="comment1" name="comment" required="required"><br>
      <label for="comment2">evaluate second product</label><br>
    <input type="text" id="comment2" name="comment" required="required"><br>
      <label for="comment">evaluate third product</label><br>
    <input type="text" id="comment" name="comment" required="required"><br>
     <input type="submit" value="Submit">
</form>

 <h4 style="color:Violet;">
   {{ prediction_text }} </h4>

</body>
</html>

当我运行它的时候,得到的输出是:

在这里输入图片描述

在这个表单里,我写了三段文字,但它只显示了一段。这里是对应的使用 Flask 的 Python 代码:

import numpy as np
from flask import Flask,request,jsonify,render_template
import pickle
from transformers import pipeline

app = Flask(__name__)
@app.route('/')
def home():
    return render_template("Commenting.html")

@app.route('/predict',methods=['POST'])
def predict():
    text =  [x for x in request.form.values()]
    # text=list(text)
    return render_template('Commenting.html', prediction_text=text)
    # sentiment_pipeline = pipeline("sentiment-analysis")
    # result =sentiment_pipeline(text)[0]
    # if result['label']=='POSITIVE':
    #     return render_template('Commenting.html',prediction_text=f'emotion of comment is positive')
    # else:
    #     return render_template('Commenting.html', prediction_text=f'emotion of comment is not positive')

if __name__ =="__main__":
    app.run()

你能告诉我为什么我只能看到第一段文字吗?其他的文字都去哪儿了?

1 个回答

0

通常,当你提交表单时,浏览器会收集数据并把它发送到服务器。不过,因为这三个输入框的名字都一样(name="comment"),所以它们的数据会互相覆盖,最后只会保留最后一个输入框的数据。

你需要给每个输入框一个独特的名字。

可以像这样做:

<input type="text" id="comment1" name="comment1" required="required"><br>
<input type="text" id="comment2" name="comment2" required="required"><br>
<input type="text" id="comment3" name="comment3" required="required"><br>

撰写回答