【问题标题】:ajax get nested dict from django views.py. How can i access the nested data?ajax 从 django views.py 获取嵌套字典。如何访问嵌套数据?
【发布时间】:2017-12-02 22:28:21
【问题描述】:

我使用 ajax 从 django views.py 获取嵌套字典。如何访问嵌套数据?

在views.py中

class Dash():
    def get(self, request, format=None):
        data = {'index':{'a':[1,2], 'b':[2,3]}, 'value':{'a':[2,3], 'b':[3,4]}}
        return Response(data) 

在 urls.py 中 url(r'^api/chart/data/Dash$', Dash.as_view())

在 Dash.html 中

    var endpoint = '/api/chart/data/Dash'
    var index = []
    var value = []
    $.ajax({
        method: "GET",
        url: endpoint,
        success: function (data) {
            index = data.index
            value = data.value
            setChart()
        },
        error: function (error_data) {
            console.log("error")
            console.log(error_data)
        }
    })

    function setChart() {
        var rbline = echarts.init(document.getElementById('rb-line'));
        rbline.setOption({
            xAxis: [{
                type: 'category',
                data: index['a']
            }],
            series: [{
                name: 'data',
                type: 'line',
                data: value['a']
            }]
        });
    }

没有图表显示。 我是 Jquery 的新手,有人可以帮助我吗?

【问题讨论】:

    标签: ajax django


    【解决方案1】:

    您可以将数据转储为 json,还需要指定要返回的内容类型是 json。 javascript 将为您完成剩下的工作。

    import json
    from django.http import HttpResponse
    
    def get(self, request, format=None):
        data = {'index': {'a': [1, 2], 'b': [2, 3]}, 'value': {'a': [2, 3], 'b': [3, 4]}}
        json_data = json.dumps(data)
    
        return HttpResponse(json_data, content_type='application/json)
    

    然后你可以在你的ajax中访问它:

    success: function(data){
        var index = data.index;
        var value = data.value;
        var a = data.index['a']
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-24
      • 2018-12-06
      • 1970-01-01
      • 2019-11-07
      • 2022-01-05
      • 2020-10-01
      • 2021-05-10
      • 1970-01-01
      • 2015-03-23
      相关资源
      最近更新 更多