Python:flask框架下前后端的数据交互


前提

后端:python 的 flask 框架
前端:html、css、js

一、前端发送数据,后端接受数据

1.1 路由传参数(数据)

  • 方法一:

前端(html):

<a href="{{url_for('choose', message_i=key, message_j=val)}}">供应商</a>    
// 注意choose是路由所在的函数,不是路由

后端(python):

@app.route('/deal_rb/<key>,<val>', methods=['POST', 'GET'])
def choose(key,val)
	###
  • 方法二:

前端(html):

<a href="/detail/{{key}}/{{val}}">查看详细信息</a>
// 这里的detail是路由

后端(python):

@app.route('/detail/<key>/<val>', methods=['POST', 'GET'])
def DeleteTag(key,val):
	###

1.2 表单提交

前端(html):

<form action="http://localhost:5000/adm_user/query_r/" method="POST">
	<p>
		<input type="text" name="val">
		<input type="submit" name="op" value="查询">
		<input type="submit" name="op" value="显示全部">
	</p>
 </form>

表单可采用 “POST” 和 “GET” 两种提交方式,“POST” 比较常用,所以这里采用。注意这里有两个 submit 提交。

后端(python):

@app.route('/adm_user/query_r/', methods=['POST', 'GET'])
def query():
    if request.method == 'POST':
    	th = request.form["op"]
    	val = request.form["val"]
    	if th == "查询":
        	###
    	elif th == "查询全部":
        	###
	elif request.method == 'GET':
        th = request.args.get("op")
        val = request.args.get("val")
        if th == "查询":
        	###
    	elif th == "查询全部":
        	###

二、后端发送数据,前端接受数据

后端(python):

from flask import render_template

@app.route('/adm_user/reader/')
def reader():
    data = {
    	1: ['10001', '123', 'Mike', '男', '21'],
    	2: ['10002', '123', 'Sam', '男', '25'],
    	3: ['10003', '123', 'hong', '女', '20']
	}
    return render_template('reader.html', data_dict=data, status="error")

datastatus 是想要发送到前端的数据,我的数据 data 是字典,status 是字符串。同时前端 reader.html 接受数据。

前端(html):

<table>
	{% for k,v in data_dict.items() %}
		<tr>
			<td>{{k}}</td>
			<td>{{v[0]}}</td>
			<td>{{v[1]}}</td>
			<td>{{v[2]}}</td>
			<td>{{v[3]}}</td>
			<td>{{v[4]}}</td>
		</tr>
	{% endfor %}
</table>

{% if status == "error" %}
	<script>
		alert("操作失败!")
	</script>
{% endif %}

这里我直接用嵌入式的 forif 语句来输出后端传来的数据。

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值