简体   繁体   中英

I've created a list in python but how do I iterate through this list in javascript?

I create a list in python and then have converted it to json. But I'm having trouble iterating through this in javascript and displaying the correct items.

Any advice?

python:

def friends2(request):
    fb_feed = [#data in here]
    b = json.dumps(fb_feed)
    print b
    return HttpResponse(b)

what is printed in the console when I print b :

[
    [1236870349, "Your friend", "Bhangra indian Jingle Bells balle balle Merry Christmas", "2lPdXV1KO4s", "Your friend watched \"Bhangra indian Jingle Bells balle balle Merry Christmas\""], 
    [2303218, "Your friend", "Look at this Instagram (Nickelback Parody)", "ttp://www.c", "Your friend watched \"Look at this Instagram (Nickelback Parody)\""]

]

javascript

    <script>
$(document).ready(function (){

            event.preventDefault();
            $.ajax({
                 type:"GET",
                 url:"/friends2/",
                 data: {},

                 success: function(b){
                    b = jQuery.parseJSON(b);
                                            console.log(b) //returns null
                    for (var i = 0; i < b.length; i++) { 
                            var friend = "";
                            friend = b[i][3]
                            friend += "\n";
                            $('.social').append(friend);
                        }                

                    }
            });
});
</script>

html

<div class = 'social'></div>

Add dataType:json to $.ajax script

 $.ajax({
         type:"GET",
         url:"/friends2/",  #the url /friends2/ points to friends2 in python
         data: {},
         dataType: json, //ADD THIS
         ...
         ...

If you don't want to add dataType then you can use jQuery.parseJSON(b) to parse your json string,

success: function(b) {
    var data = jQuery.parseJSON(b); //parse JSON string here
    ...
    ...

}

I think there is a mistake in your code. the json should be correct. b[3] is undefined, as the array is of length 2. did you mean b[i][3]?

everything else should work as far as i can tell.

If your view is returning JSON, you should set the content type (MIME type) accordingly:

return HttpResponse(b, content_type='application/json')

jQuery's $.ajax is smart enough to automatically apply dataType: json when the MIME type is set correctly:

dataType

Default: Intelligent Guess (xml, json, script, or html)

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM