Flask获取用户输入并返回结果
开发网页的过程中,最常使用的功能就是获取用户输入,对用户输入进行一定处理后再返回到前端界面。
PyCharm 新建flask工程
其中,static文件中存放js文件,templates文件汇总存放html文件
HTML文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
<link rel="shortcut icon" href="#" />
{# 都是必须要写的,写自己文档复制粘贴过去就行#}
<script src="/static/jquery-3.5.1.js"></script>
{# 引入jquert的标准文件#}
<script src="/static/index.js"></script>
{# 引入对应的js文件#}
</head>
<body>
{# body里写自己的HTML内容#}
<h2>关系抽取</h2>
<input type = "text" name="input_sentence" id="input_sentence" value="Like Siegfried Sassoon, Schuster was of Jewish descent."></input>
<p name="output_sentence" id="output_sentence"></p>
<button id="button">提交</button>
</body>
</html>
JS文件
jquery语法可以参考Jquery|菜鸟教程
$(document).ready(function(){
$("#button").click(function()
{
$.post("/index",
{
"sentence":$("#input_sentence").val(),
},
function(data,status)
{
// alert(data.sentence);
$("#output_sentence").text(data.sentence)
});
});
})
app.py
from flask import Flask,jsonify,request,render_template
app = Flask(__name__)
@app.route('/')
def hello():
return render_template("index.html")
@app.route('/index', methods=['POST'])
def index():
sentence = request.form['sentence']
res = sentence + "hhhhh"
return jsonify({'sentence': res})
结果展示
点击按钮提交后