python使用flask与js进行前后台交互的例子

yipeiwu_com5年前Python基础

flask与js进行前后台交互代码如下,后台给前端发数据:

python部分:

# -*- coding: utf-8 -*-
from flask import Flask,jsonify,render_template
import json
 
app = Flask(__name__)#实例化app对象
 
testInfo = {}
 
@app.route('/test_post/nn',methods=['GET','POST'])#路由
def test_post():
  testInfo['name'] = 'xiaoming'
  testInfo['age'] = '28'
  return json.dumps(testInfo)
 
@app.route('/')
def hello_world():
  return 'Hello World!'
 
@app.route('/index')
def index():
  return render_template('index.html')
 
 
if __name__ == '__main__':
  app.run(host='0.0.0.0',#任何ip都可以访问
      port=7777,#端口
      debug=True
      )

js部分:

<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>echarts</title>
  <style type="text/css">
    html,
    body {
      width: 100%;
      height: 100%;
    }
 
    body {
      margin: 0px;
      padding: 0px
    }
 
    div {
      float: left;
    }
 
    #container {
      width: 50%;
      height: 100%;
    }
 
    #info {
      padding: 10px 20px;
    }
  </style>
</head>
 
<body>
  <div id="container"></div>
  <div id="info">数据展示:</div>
  <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script>
	<script>
    $.ajax({
    url: "test_post/nn",
    type: "POST",
    dataType: "json",
    success: function (data) {
      console.log(data)
    }
    })
 
	</script>
  
</body>
 
</html>

以上这篇python使用flask与js进行前后台交互的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

浅谈Python基础—判断和循环

浅谈Python基础—判断和循环

判断 缩进代替大括号。 冒号(:)后换号缩进。 if test=100 if test>50: print('OK') print('test') if-elif-els...

解决pycharm 工具栏Tool中找不到Run manager.py Task的问题

解决pycharm 工具栏Tool中找不到Run manager.py Task的问题

在做Django项目的过程中, 无法进入pycharm提供的Run manager.py Task交互环境 出现这种问题是因为Pycharm无法识别这个项目是django项目.需要进行配...

python celery分布式任务队列的使用详解

python celery分布式任务队列的使用详解

一、Celery介绍和基本使用 Celery 是一个 基于python开发的分布式异步消息任务队列,通过它可以轻松的实现任务的异步处理, 如果你的业务场景中需要用到异步任务,就可以考...

Python 3.6 性能测试框架Locust安装及使用方法(详解)

Python 3.6 性能测试框架Locust安装及使用方法(详解)

背景 Python3.6 性能测试框架Locust的搭建与使用 基础 python版本:python3.6 开发工具:pycharm Locust的安装与配置 点击“File”→“s...

微信跳一跳辅助python代码实现

微信跳一跳辅助的python具体实现代码,供大家参考,具体内容如下 这是一个 2.5D 插画风格的益智游戏,玩家可以通过按压屏幕时间的长短来控制这个「小人」跳跃的距离。可能刚开始上手的时...