如何在ajax中访问django对象

时间:2017-04-08 17:37:14

标签: jquery ajax django

我想在ajax代码中访问django对象。但我无法访问它。请指导我。

  

我的服务器代码

def attendance_table(request):
    if request.is_ajax():
        try:
            CollegeCode = request.session.get('collegeCode')
            academicyear = logic.academicYearCal()
            eventquery = "SELECT e.EventId , e.EventLocation,e. EventStartDate,e.EventEndDate,e.EventHours,em.EventCode as EC ,em.EventName from Events "
            events = models.Events.objects.raw(eventquery, [academicyear, '1', CollegeCode])

            context = {}
            events = serializers.serialize('json', events)
            context['events'] = events

            return JsonResponse(data=context)

        except Exception as e:
            return JsonResponse(data={'error':'error'})


  

Ajax代码

$.ajax({
        url:url,
        type:'GET',
        dataType:'JSON',
        success:function(response) {
            console.log(response.events);
        }
    });


在浏览器控制台中,输出是

[{"model": "sample.events", "pk": "E22", "fields": {"eventcode": "1", "collegecode": "KIT", "eventopenflag": "1", "eventstartdate": "2017-07-23", "eventenddate": "2017-07-22", "eventlocation": "Shivaji memorials , kolhapur", "academicyear": "2017", "eventlevel": 5, "eventhours": 0}}]

请纠正我..

1 个答案:

答案 0 :(得分:0)

你可以像{python字典一样access a javascript object

因为你要返回一个数组,所以你必须首先迭代它。假设您将返回的数组命名为response.events,那么:

success:function(response) {
    // convert String to JSON object (JS object)
    var events = JSON.parse(response.events);  // events should be an Array (console.log(events instanceof Array) should yield True)
    for (var i=0; i<events.length; i++) { 
        // now each events[i] has an object within it
        var obj = events[i];  // obj is an alias for each object in the array
        // Now you can access each key-value pair like this
        var fields = obj.fields;  // an alias again
        var eventcode = fields.eventcode;  // or fields['eventcode']
        var collegecode = fields.collegecode;
        // etc.
    }

请注意,如果您的数组总是包含一个对象,那么您不需要for循环。只需将对象放入其中:

success:function(response) {
    var events = JSON.parse(response.events);
    var obj = events[0];
    var fields = obj.fields;
    ...
}