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

演示效果:

相关推荐
kfaino5 小时前
码农的AI翻身(五)你好,我叫 Transformer
后端·aigc
Oneslide11 小时前
机械革命 单系统纯净重装Ubuntu(全盘覆盖,清空原有Windows)
后端
GetcharZp11 小时前
告别OOM!用Go+libvips实现30000×50000超大图片的流式瓦片服务
后端·go
IT_陈寒11 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
用户479492835691512 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
神奇小汤圆13 小时前
2026一线大厂Java八股文精选(附答案,高质量整理)
后端
Warson_L13 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅13 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅14 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L14 小时前
LangGraph的MessageState and HumanMessage
python