Seyyid Said
Seyyid Said

Reputation: 525

How to Loop through an array with object using jquery

I have been practising with pure Django (django without js) for a while now.I have therefore decided to go some step further to include Jquery Ajax in my django.Where i can be able to insert some data dynamically into my html.

The problem however is looping through the django model response using jquery ajax is not working for me. below is my jquery.Somebody help to through the array using jquery.

    function ajaxLoad(item){

    $.ajax({
        type:  'POST',
        url :   '../ajax/fetch_category/',
        data: {
            'parameter':item
        },
        cache:false,
        dataType: 'json',
        success: function(response_data) {
        //This is an example of respone data i get from ajax , though was created manually
        var data = [
            {
                "model": "gallery.photogallery",
                "pk": 2,
                "fields": 
                    {
                        "title": "This is my title", 
                        "picture_choices": "Urban", 
                        "description": "This is my good description .",
                        "user": 2, 
                        "date_posted": "2018-06-13T20:13:57.774Z",
                        "views": 3,
                        "likes": 2, 
                        "country": "AG",
                        "slug": "this-is-my-title"
                    }
            }

        ];
       //here am looping through the array
        for( item in data){
            console.log(item);
            $.each(item, function( key, value ) {
                console.log( key + ": " + value );
            });
        }


        },
        error: function(XMLHttpRequest,textStatus,errorThrown) {
            console.log("XMLHttpRequest", XMLHttpRequest);
            console.log("textStatus", textStatus);
            console.log("errorThrown", errorThrown); 
        }
    });
}

Upvotes: 0

Views: 424

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599788

The dataType parameter of the ajax method in jQuery sets the type of the data you are expecting back from the server. You have set it to "text", which means that jQuery will treat the response just as pure text. This is not useful, especially if you want to treat it as an object and iterate through its keys.

Although you have not shown your view, which would have been useful, I presume you are actually sending JSON. In which case, you should set that parameter to "json" - or leave it out completely, in which case jQuery will make an intelligent guess.

Upvotes: 1

shmee
shmee

Reputation: 5101

What you get from Django depends on what you return in your views. Using the render() shortcut, you get an HttpResponse object.

For Ajax, I tend to return JsonResponse objects.

If you return pure Querysets, you'll have to pass them through a serializer first.

Upvotes: 0

Related Questions