I'm trying to get an array of objects from Django Database through AJAX but I'm not getting how to parse back to JSON

Viewed 71

I want to get few indexes every time, pressing Next and Previous Button

So here is the view:

class RetrieveCrudUser(View):
    def get(self, request):
        fromIndex = int(request.GET.get('fromIndex', None))
        toIndex = int(request.GET.get('toIndex', None))
        print("from index: "+str(fromIndex))
        print("to index: "+str(toIndex))
        if fromIndex > CrudUser.objects.all().count()-1:
            print("entered in the if")
            fromIndex = 0
            toIndex = 2

        elif toIndex > CrudUser.objects.all().count()-1:
            print("entered in the elif")
            toIndex = CrudUser.objects.all().count()-1

        users = serializers.serialize("json",CrudUser.objects.all().order_by('id')[fromIndex:toIndex])
        print(type(users))
        data = {
            'users': users,
            'fromIndex': fromIndex,
            'toIndex': toIndex
        }
        return JsonResponse(data)

And here, the javascript:

function showNext(){
  fromIndex+=3
  toIndex+=3
  $.ajax({
    url: "{% url 'crud_ajax_retrieve' %}",
    data: {
      'fromIndex' : fromIndex,
      'toIndex' : toIndex,
      dataType: 'json',
    },
    success: function (data) {
      fromIndex = data.fromIndex
      toIndex = data.toIndex
      let temp = JSON.parse(data.users)
      console.log(temp)
      // TODO: clear table html #tbody
      // TODO: for each user append to the table
    }
  })
}

And this is what it prints (the temp variable) -> And it says the datatype is Object (I don't understand why it is not an array) I want to get an array of those "fields" keys as user objects.

PRINT OF GOOGLE CHROME CONSOLE

0 Answers
Related