向服务器发送数据 Flask HTML

2 投票
1 回答
2362 浏览
提问于 2025-04-17 15:17

我正在尝试创建一个简单的复选框,能够将数据发送到服务器,这里是我的HTML代码。

<form action="." method="POST">
<div class="checksheet">

    <input id="XML Parser" class="checkbox" type="checkbox"/>XML Parser
    <input id="Feed Parser" class="checkbox" type="checkbox"/>Feed Parser
    <input id="Text Parser" class="checkbox" type="checkbox"/>Text Parser
    <input id="Case Normalization" class="checkbox" type="checkbox"/>Case Normalization
    <input id="Stemmer" class="checkbox" type="checkbox"/>  Stemmer

</div>

<div class="submit"><input type="submit"  value="Send" name="raw_text"></div>
</form>

我想做的事情和这里提问的内容非常相似:如何将数据从文本框发送到Flask? 只是我用的是复选框,而不是文本框。

但是我遇到了这个错误:

Not Found

The requested URL was not found on the server.

If you entered the URL manually please check your spelling and try again.

我的服务器端代码(使用Flask)是:

@app.route('/raw_text.html')
def home ():
    file = "sample.xml"
    contents = open(file).read()

    contents = contents.decode('utf-8')
    return render_template('raw_text.html',  contents=contents,file=file)

@app.route('/raw_text.html',methods=['POST'])
def get_data():
    print "REQUEST ",request.form()
    data = request.form['raw_text']
    print data
    return "Processed"

有什么建议吗?谢谢!

1 个回答

2

几点注意事项:

  1. 你的复选框元素需要有一个 name 属性,这个属性在数据发送到后台时会用到。每个相关的复选框都需要有相同的 name

  2. 你的 action 属性需要指向一个网址。如果你是把表单提交到同一个页面,可以把这个属性去掉。

  3. ID 中不能有空格。

  4. 为了让复选框更易于访问,需要加上 <label> 标签。

撰写回答