提供基于js与python利用ajax传输json数据的部分示例:
在static文件js目录下:
jquery.js
st_goods.js
HTML页面:
<!DOCTYPE html> {% load staticfiles %} <html> <head> <meta charset="utf-8"> <title>ECharts</title> </head> <body> <div id="goods_statistics">商品统计</div> <!-- 为ECharts准备一个具备大小(宽高)的Dom --> <div id="main" style="height:400px"></div> <!-- ECharts单文件引入 --> <script src="http://echarts.baidu.com/build/dist/echarts.js"></script> <script src="{% static ‘js/jquery.js‘ %}"></script> <script src="{% static ‘js/st_goods.js‘ %}"></script> </script> </body> </html>
JS页面
//商品统计 $("#goods_statistics").click(function(){ $.ajax({ type: ‘get‘, url: base_url + ‘/statistics/goods_st‘, data : {}, success: function(e){ result = JSON.parse(e); goods_st_sort(result.goods_st); } }) }); //商品名 var g_name = []; //关注 var marked = []; //收藏 var collected = []; //购买 var purchased = []; //浏览 var browse = []; function goods_st_sort(goods_st){ var arr = new Array(); for(var i = 0 ; i < goods_st.length ; i++){ arr = goods_st[i].toString().split(‘,‘); g_name.push(arr[0]); //console.log(name[i]); marked.push(arr[1]); collected.push(arr[2]); purchased.push(arr[3]); browse.push(arr[4]); } draw(); //console.log(name.length); }
Python代码
#用户行为分析图 def goods_st_pic(request): return render(request,website.goods_st_pic,None) #用户行为数据 def goods_st(request): #连接数据库 conn = MySQLdb.connect(host=‘120.26.38.125‘,user=‘root‘, passwd=‘passw0rd‘,db=‘jkbrother3‘,charset=‘utf8‘) sql = "select distinct(g.name), g.marked_count, g.collected_count, g.purchased_count, (select sum(count) from adminer_access_record where mold =‘0‘ and action_id =g.id) browse_count from adminer_goods g, adminer_access_record ar where g.id=ar.action_id" cur = conn.cursor() #执行sql cur.execute(sql) #列出数据 records = cur.fetchall() result = [] for row in records: temp = (row[0],row[1],row[2],row[3],row[4]) result.append(temp) conf = {‘goods_st‘:result} #关闭连接 cur.close() conn.close() return HttpResponse(json.dumps(conf)) 注意带参数传值,字典: var tdata = {"time":"2015-05-17"}; //商品统计 $("#traffic_statistics").click(function(){ $.ajax({ type: ‘post‘, url: base_url + ‘/statistics/traffic_st‘, data : tdata, success: function(e){ result = JSON.parse(e); print(result.traffic_st); } }) }); #网站流量统计 def traffic_st(request): time = request.POST["time"] #连接数据库
原文地址:http://wangjh.blog.51cto.com/7013550/1657362