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

演示效果:

相关推荐
万少1 分钟前
AtomCode开发微信小程序《谁去呀》 全流程
前端·javascript·后端
GetcharZp2 分钟前
Epic、暴雪都在用的 C++ 界面利器:Dear ImGui 零基础全景指南
后端
某人辛木16 分钟前
Web自动化测试
前端·python·pycharm·pytest
C+++Python38 分钟前
详细介绍一下Java泛型的通配符
java·windows·python
pixcarp1 小时前
知识库系统的内容资产闭环怎么设计
服务器·数据库·后端·golang
红尘散仙1 小时前
别再手动录屏了:用 VHS 给终端应用生成会动的文档素材
后端·rust
小帅热爱难回头1 小时前
编写Skill生成AI落地项目系统架构
python
diving deep2 小时前
脚本速览-python
开发语言·python
2601_951643773 小时前
Python第一,Java跌出前三,C语言杀回来了
java·c语言·python·编程语言排行·技术趋势
张忠琳4 小时前
【Go 1.26.4】Golang Select 深度解析
开发语言·后端·golang