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

演示效果:

相关推荐
卷无止境15 分钟前
python进阶:类方法与静态方法的分野,classmethod 和 staticmethod 到底该怎么选
后端·python
AINative软件工程17 分钟前
LLM 应用的分层可观测性工程实践:从 Span 到 Prompt Diff,三层 Trace 让 AI 系统真正可调试
后端·ai编程
卷无止境19 分钟前
继承与多态:Python OOP里最容易被用错的两把梯子
后端·python
SelectDB技术团队25 分钟前
丰巢日志平台 ELK 替代:Apache Doris / SelectDB 的技术能力与实践
开发语言·python
明月_清风26 分钟前
📊 Tokenomics 入门:如何看懂一个项目的代币经济?
后端·web3
崖边看雾29 分钟前
Python学习——函数
开发语言·windows·python·学习·pycharm
明月_清风32 分钟前
🏛️ DAO 治理入门:没有老板的公司怎么运转?
后端·web3
yuhaiqiang39 分钟前
上线一个人静态网站需要多少钱,难不难?
前端·后端·程序员
深念Y42 分钟前
Windows幽灵端口占用:HNS如何无声偷走你的端口
windows·python·bug·环境·端口·特权