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

演示效果:

相关推荐
XS030106几秒前
Spring框架
java·后端·spring
风吹心凉几秒前
python3基础2026.7.28
开发语言·python
xcLeigh6 分钟前
Go入门:main包与main函数的特殊地位
开发语言·后端·golang
曲无忆14 分钟前
LLMs赋能依赖类型证明自动化
python
一次旅行32 分钟前
act本地预跑GitHub Actions:Python项目完整CI/CD流水线实战
python·ci/cd·github
Darren24539 分钟前
JWT、OAuth 2.0 与 SSO 详解
后端
玉鸯40 分钟前
RAG 全链路调优指南:从 Chunking 到 Reranker
python·llm·agent
SelectDB1 小时前
Apache Doris / SelectDB 实时分析三大范式:技术能力、选型对比与企业实践
后端
圣光SG1 小时前
Java操作题练习(二)
java·开发语言·python
m0_617493941 小时前
Python OpenCV 分水岭算法(Watershed)详解与实战
python·opencv·算法