企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
https://segmentfault.com/a/1190000007605055 最近在学习Python的flask微框架,用到最多的就是和前端针对REST API进行交互,那么自然而然传递Json就成为了家常便饭,特意总结了一下和前端交互几种方法。 ### 1\. 利用flask的**request.form.get()**方法 这一中方法主要利用flask的**request.form.get**方法,获得前端发送给后台的json文件 Python 端代码: ~~~ @app.route('/sendjson', methods=['POST']) def sendjson(): # 接受前端发来的数据 data = json.loads(request.form.get('data')) # lesson: "Operation System" # score: 100 lesson = data["lesson"] score = data["score"] # 自己在本地组装成Json格式,用到了flask的jsonify方法 info = dict() info['name'] = "pengshuang" info['lesson'] = lesson info['score'] = score return jsonify(info) ~~~ JS代码: ~~~ <script> $(document).ready(function () { var data = { data: JSON.stringify({"lesson": "Operation System", "score": 100}) } $.ajax({ url:"/sendjson", type: 'POST', data: data, success: function (msg) { alert(msg.name) } }) }); </script> ~~~ ### 2\. 利用flask的**request.get_data()**方法 Python端代码: ~~~ @app.route('/sendjson2',methods=['POST']) def sendjson2(): # 接收前端发来的数据,转化为Json格式,我个人理解就是Python里面的字典格式 data = json.loads(request.get_data()) # 然后在本地对数据进行处理,再返回给前端 name = data["name"] age = data["age"] location = data["location"] data["time"] = "2016" # Output: {u'age': 23, u'name': u'Peng Shuang', u'location': u'China'} # print data return jsonify(data) ~~~ 相比第一种方法JS的代码,这一种更常见也更容易理解一些,在前端组织好Json,再传递给后台 JS代码: $(document).ready(function () { var student = new Object(); student.name = &quot;Peng Shuang&quot;; student.age = 23; student.location = &quot;China&quot;; var data = JSON.stringify(student) $.ajax({ url: &quot;/sendjson2&quot;, type: &quot;POST&quot;, data: data, success: function (msg) { alert(msg.time) } }) }) " title="" data-original-title="复制" style="box-sizing: border-box; cursor: pointer; display: block; float: left; background-image: url(&quot;../img/codeTools.svg&quot;); height: 16px; width: 16px; background-size: auto 16px; margin: 4px 5px; opacity: 0.5; background-position: -16px 0px !important;"> ~~~ <script> $(document).ready(function () { var student = new Object(); student.name = "Peng Shuang"; student.age = 23; student.location = "China"; var data = JSON.stringify(student) $.ajax({ url: "/sendjson2", type: "POST", data: data, success: function (msg) { alert(msg.time) } }) }) </script> ~~~