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

yipeiwu_com6年前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遍历文件夹和读写文件的实现方法

需 求 分 析 1、读取指定目录下的所有文件 2、读取指定文件,输出文件内容 3、创建一个文件并保存到指定目录 实 现 过 程 Python写代码简洁高效,实现以上功能仅用了40行左右...

使用Python的Dataframe取两列时间值相差一年的所有行方法

在使用Python处理数据时,经常需要对数据筛选。 这是在对时间筛选时,判断两列时间是否相差一年,如果是,则返回符合条件的所有列。 data原始数据: data[map(lambda...

Python Excel处理库openpyxl使用详解

openpyxl是一个第三方库,可以处理xlsx格式的Excel文件。pip install openpyxl安装。 读取Excel文件 需要导入相关函数 from openpy...

几种实用的pythonic语法实例代码

前言 python 是一门简单而优雅的语言,可能是过于简单了,不用花太多时间学习就能使用,其实 python 里面还有一些很好的特性,能大大简化你代码的逻辑,提高代码的可读性。 所谓Py...

Apache,wsgi,django 程序部署配置方法详解

Apache,wsgi,django 程序部署配置方法详解

本文实例讲述了Apache,wsgi,django 程序部署配置方法。分享给大家供大家参考,具体如下: 前面写过一篇文章,ngixn,uwsgi,django,python 环境配置,有...