Django和ECharts异步请求示例

前提条件

创建django项目,安装配置过程这里就不讲述了。

后端url

http://127.0.0.1:8000/echarts/demo/

view视图函数

python 复制代码
from django.http import HttpResponse
import json

def EchartsDemo(request):
    data = {}
    categories = ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
    values = [5, 20, 36, 10, 10, 20]

    data['categories'] = categories
    data['values'] = values

    return HttpResponse(json.dumps(data), content_type="application/json")

前端页面

需要分别引入jquery、echarts,顺序jquery在前

html 复制代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>echarts示例</title>		
		<script src="jquery.min.js"></script>
		<script type = "text/javascript" src = "echarts.min.js" ></script>		
	</head>
	
	<body>				
		<div id="main" style="width: 800px;height:600px;"></div>
		<script type="text/javascript">
			var myChart = echarts.init(document.getElementById('main'));
			
			$.get('api/echarts/demo/').done(function(data) {
			  // data 的结构:
			  // {
			  //     categories: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"],
			  //     values: [5, 20, 36, 10, 10, 20]
			  // }
			  myChart.setOption({
			    title: {
			      text: '异步数据加载示例'
			    },
			    tooltip: {},
			    legend: {},
			    xAxis: {
			      data: data.categories
			    },
			    yAxis: {},
			    series: [
			      {
			        name: '销量',
			        type: 'bar',
			        data: data.values
			      }
			    ]
			  });
			});
		</script>
	</body>
</html>

跨域问题

html浏览器不支持跨域请求,这里采用nginx。

html 复制代码
server {
            listen       80;
            server_name  localhost;

            #charset koi8-r;

            #access_log  logs/host.access.log  main;

            location / {
                root   html;
                index  index.html index.htm;
            }
	        location /api {
                rewrite  ^.+api/?(.*)$ /$1 break;
                proxy_pass  http://127.0.0.1:8000;
            }
       }

演示效果:

相关推荐
weixin_4407841140 分钟前
Java基础常见题
java·开发语言·python·java基础
Lihua奏1 小时前
跨域:浏览器到底拦住了什么
后端
跨境小彭1 小时前
Python列表去重的6种高效方法(含保留顺序+性能对比)
开发语言·python
今天AI了吗1 小时前
Python 基础语法从入门到使用详解
开发语言·人工智能·python
Lyra_Infra1 小时前
Docker OCI Runtime 启动失败问题排查与解决
后端·docker·架构
苏灿烤鱼1 小时前
从微信公众号内容到视频号视频:自动化视频生成的技术实现
人工智能·python·ffmpeg
XuCoder1 小时前
Redis 哨兵模式:它到底是怎么保证高可用的
后端
金銀銅鐵2 小时前
[Python] 借助 Pillow 和 NumPy 生成与斐波那契数列有关的图案
python·数学
雪之下雪乃的代码日记2 小时前
Python快速入门(Java开发者版)
java·开发语言·笔记·python
敲个大西瓜2 小时前
Springboot核心面试题
java·spring boot·后端