失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > flask框架前后端数据交互

flask框架前后端数据交互

时间:2024-07-06 05:12:48

相关推荐

flask框架前后端数据交互

flask开发中需要用到ajax进行前端数据交互,主要流程为三步:

前端引用js文件,调用其中函数后端完成调用数据库函数并设置数据格式js中使用ajax请求接收数据,并将返回的数据显示到前端

代码展示:

前端引用js文件,调用其中函数

方法一:直接在html文件中插入js代码

<script type="text/javascript">//function</script>

方法二:单独写一个js文件,再引入到html中,建议此方式。

<!--html页面中引入--><script src="{{ url_for('static', filename='js/jsFileName.js') }}"></script><!--调用方式参考--><a href='#' data-toggle='modal' data-target='#myModal' onclick='function()'>点击</a>

注:如果是调用js文件,一定一定一定要记得在浏览器中强制刷新 Ctrl+F5,不然会缓存原有js文件,修改的代码无法生效,建议在浏览器中打开那个js文件,每次运行程序前手动刷新一下,当时试过设置浏览器 Diable cache ,但貌似无效。

后端完成调用数据库函数并设置数据格式

@route('/funcitonUrl', methods=['GET'])def function():topics = session.query(Topics).all()tp_list = []# print(type(topics))for topic in topics:tp_list.append({"id": topic.id, "text": topic.text})# print(type(tp_list))# print(tp_list)return json.dumps(tp_list)

这里需要注意设置好传输数据的格式,最后返回使用 json.dumps.

js中使用ajax请求接收数据,并将返回的数据显示到前端

var topic = [{id: 0,text: '内容',}];var sendData = JSON.stringify(topic);// console.log("sendData " + sendData);var xmlHttpRequest;function createXMLHttpRequest() {if (window.XMLHttpRequest) //非IE浏览器{xmlHttpRequest = new XMLHttpRequest();} else if (window.ActiveObject)//IE6以上版本的IE浏览器{xmlHttpRequest = new ActiveObject("Msxml2.XMLHTTP");} else //IE6及以下版本IE浏览器{xmlHttpRequest = new ActiveObject("Microsoft.XMLHTTP");}}function sendRequest(url) {createXMLHttpRequest();xmlHttpRequest.open("GET", url, true);xmlHttpRequest.onreadystatechange = processResponse;xmlHttpRequest.send(null);}sendRequest("/funcitonUrl");function processResponse() {if (xmlHttpRequest.readyState == 4) {if (xmlHttpRequest.status == 200) {var resp = xmlHttpRequest.responseText;// alert("111111" + resp);$.ajax({type: "GET",url: "/funcitonUrl", //后端请求data: sendData,dataType: "json",async: true,success: function (data) {// console.log(typeof data);// console.log(data);//alert('2222' + data);var topic;$.each(data, function (i, values) {topic = "<tr><td>" + values.id + "</td>"+ "<td>" + values.text + "</td></tr>";$('.table').append(topic);},error: function (errorInfo) {console.log("errorInfo\n" + errorInfo);}});}}}var i = 0;//设置定时器(循环去执行)var timeId = setInterval(function () {i++;processResponse();//console.log('定时运行:' + i + '次')}, 500);setInterval(function () {window.clearInterval(timeId);//console.log(''清理:' + i + '次'')}, 500);timeId = setInterval(function () {i++;processResponse();//console.log('定时运行:' + i + '次')}, 500);

一定要先设置好接收的数据格式,并将其转换为JSON字符串,不然接收过来很难处理。最后三个函数是设置和清理定时器,具体说明可见 参考文章【5】

参考文章:【1】python通过flask和前端进行数据收发

 【2】前端与后端的数据交互(jquery ajax+python flask)

 【3】python flask 通过ajax向后台传递数组参数

 【4】Ajax返回的json遍历取值并显示到前台

 【5】js中定时器的设置和清理

如果觉得《flask框架前后端数据交互》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。