直接代码展示:
view.py文件代码
from django.http import JsonResponse #django ajax部分 def ajax_kchart(request): times = request.POST['shijian'] chnl = request.POST['chnl'] chnl_data = keywork_chart(chnl,times) data_list = [] for j in chnl_data: data_list.append(j) return JsonResponse(data_list,safe=False)
这里重点关注两点 ajax_kchart函数名 和 JsonResponse(data_list,safe=False)返回json的函数
ajax_kchart函数名需要出现在url配置中,Django 1.7 及以后的版本才可以用到JsonResponse,若返回参数是列表,要令safe=False
url.py代码:
url(r'^workchart/$', 'keywork.views.ajax_kchart', name='ajax_kchart'),
模板代码:
{% load staticfiles %} <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <script src="{% static 'js/jquery/jquery.min.js' %}"></script> <script src="{% static 'js/Highcharts/js/highcharts.js' %}"></script> <script> $(document).ready(function(){ $("#btn3").click(function(){ $.post("{% url 'ajax_kchart' %}", { csrfmiddlewaretoken:"{{ csrf_token }}", shijian:$("#shijian3").val(), chnl:$("#mkt_chnl").val(), }, function (data,status) { var day_id = []; var ydxz = []; var ydjz = []; var kdxz = []; var kdjz = []; var dsxz = []; var dsjz = []; var lbdg = []; var sjqz = []; var sjxz = []; var ftth = []; for (var i = 0; i <= data.length - 1; i++) { var cdma_jz = data[i].cdma_xz + data[i].cdma_zdcj; var adsl_jz = data[i].adsl_xz + data[i].adsl_zdcj; var iptv_jz = data[i].iptv_xz + data[i].iptv_zdcj; var pstn_jz = data[i].pstn_xz + data[i].pstn_zdcj; $("#zhiju").html(data[i].mkt_chnl_name); day_id.push(data[i].day_id); ydxz.push(data[i].cdma_xz); ydjz.push(cdma_jz); kdxz.push(data[i].adsl_xz); kdjz.push(adsl_jz); dsxz.push(data[i].iptv_xz); dsjz.push(iptv_jz); lbdg.push(data[i].dlb_dg); sjqz.push(data[i].cdma_qz); sjxz.push(data[i].sjsg_xz); ftth.push(data[i].ftth_xz); }; $('#cdma_chart').highcharts({ //移动业务发展图表 chart: { type: 'line' }, title: { text: '移动业务发展量' }, xAxis: { categories: day_id }, yAxis: { title: { text: '个' } }, series: [{ name: '移动新增', data: ydxz }, { name: '移动净增', data: ydjz },{ name: '4G新增', data: sjxz } ], plotOptions: { line: { dataLabels: {//数据标签 enabled: true } }, series: {//延迟加载 animation: false } }, }); } } </script> /head> <body> <form class="form-inline"> {% csrf_token %} <label class="control-label"><i class="icon-time"></i> 时间</label> <select name="shijian3" id="shijian3" class="input-small" placeholder=".input-small"> {%for d in downlist%} <option value="{{d.day_id}}">{{d.day_id}}</option> {%endfor%} </select> <label class="control-label"><i class="icon-eye-open"></i> 支局</label> <select name="mkt_chnl" id="mkt_chnl" class="input-small" placeholder=".input-small"> {% for d in data %} <option value="{{d.mkt_chnl_id}}">{{d.mkt_chnl_name}}</option> {%endfor%} </select> <input type="button" id="btn3" value="查询" class="btn btn-primary btn-sm"/> </form> <div class="chart" id="cdma_chart"></div> </body> </html>
完毕!