我是 Flask 和 Web 开发的新手。我想在按下网页上的按钮后在本地网络服务器上显示图像。我正在使用 Flask。我已经尝试解决这个问题有一段时间了,但还没有成功,所以任何帮助都将是令人难以置信的。烧瓶代码:
@app.route('/graph_select')
def graph_select():
return render_template('live_stream.html')
@app.route('/read_ph', methods=["GET"])
def ph_plot():
if request.method == "GET":
all_plots.ph_plot()
return render_template('live_stream.html')
@app.route("/read_temp", methods=["GET"])
def temp_plot():
if request.method == "GET":
all_plots.temperature_plot()
return render_template('live_stream.html')
@app.route('/read_distance', methods=["GET"])
def distance_plot():
if request.method == "GET":
all_plots.distance_plot()
return render_template('live_stream.html')
Run Code Online (Sandbox Code Playgroud)
HTML 代码:
<h1>Data Monitoring Station</h1>
<form method="GET"
<a href="read_temp"><button type="button">Temperature Graph</button></a>
<a href="read_ph"><button type="button">PH Graph</button></a>
<a href="read_distance"><button type="button">Distance Graph</button></a>
</form>
<h3><img src="{{ url_for('static', filename='ph_plot.png') }}" width="30%">$
<h3><img src="{{ url_for('static', filename='temperature_plot.png') }}" width="30%">$
<h3><img src="{{ url_for('static', filename='distance_plot.png') }}" width="30%">$
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
太长了;
Flask我编写了一个关于使用和在按钮单击时显示图像的最小示例Ajax。
本质上,我只是将图像的 URL 返回到 HTML 页面,并使用返回的 URL 设置标签src的属性。<img>
应用程序.py:
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def hello():
return render_template('a.html')
@app.route("/getimage")
def get_img():
return "a.jpg"
if __name__ == '__main__':
app.run()
Run Code Online (Sandbox Code Playgroud)
a.html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<button type='button' id ='retrieve'>Submit</button>
<img src="" id="myimg" />
</body>
<script>
$(document).ready(function() {
$('#retrieve').click(function(){
$.ajax({
url: "{{ url_for ('get_img') }}",
type: "GET",
success: function(response) {
$("#myimg").attr('src', '/static/' + response);
},
error: function(xhr) {
//Do Something to handle error
}
});
});
});
</script>
</html>
Run Code Online (Sandbox Code Playgroud)
您可以根据需要修改此代码。
注意: a.html 文件应位于templates文件夹中,a.jpg 文件应位于static文件夹中。
希望这可以帮助。祝你好运。
| 归档时间: |
|
| 查看次数: |
5635 次 |
| 最近记录: |