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;
            }
       }

演示效果:

相关推荐
会飞的架狗师几秒前
【MySQL体系】第1篇:从MySQL架构原理到存储的解析
后端·mysql
用户8356290780511 分钟前
用Python高效处理Excel数据:Excel数据读取指南
后端·python
IT技术小密圈3 分钟前
图解系统设计: 五分钟从单体架构到微服务(上)
后端
mudtools7 分钟前
.NET驾驭Word之力:COM组件二次开发全攻略之连接Word与创建你的第一个自动化文档
后端·c#
文心快码BaiduComate7 分钟前
“一人即团队”——一句话驱动智能体团队
前端·后端·程序员
bobz96515 分钟前
kubeovn with metallb:service externalTraffcLocal
后端
小枫编程21 分钟前
Spring Boot 与前端文件上传跨域问题:Multipart、CORS 与网关配置
前端·spring boot·后端
我星期八休息24 分钟前
深入理解跳表(Skip List):原理、实现与应用
开发语言·数据结构·人工智能·python·算法·list
送秋三十五25 分钟前
spring源码分析————ListableBeanFactory
java·后端·spring
Livingbody32 分钟前
【PaddleOCR】基于PaddleOCR V5 最新框架实现车牌识别
后端