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

演示效果:

相关推荐
SomeB1oody16 分钟前
【RustyML入门】2.0. 经典机器学习
开发语言·后端·机器学习·rust·教程
大数据魔法师19 分钟前
Python 网络请求库 curl_cffi:从入门到实战,如何规避网站指纹检测
python·数据分析
就改了20 分钟前
SpringBoot 自定义线程池 + 实时监控指标
java·spring boot·后端
中电华星21 分钟前
专业的工业电源公司
网络·python
暗黑小白27 分钟前
脱敏引擎工程化
后端·ai agent
用户81818706274631 分钟前
第23章 JPA / Hibernate 异常
后端
用户81818706274632 分钟前
第22章 MyBatis / MyBatis-Plus 常见异常与 SQL 调试
后端
databook1 小时前
用统计检验来确定“重要特征”
python·机器学习·scikit-learn
雪隐1 小时前
个人电脑玩AI-15让5060 Ti给你打工——MiniMax H3 本地部署实录:一个自带录音棚的视频模型,和它的 NVFP4 瘦身奇遇
前端·人工智能·后端
0566461 小时前
Python高级——解释器执行原理与虚拟环境工程化实战
开发语言·python