Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

loop through json array jquery

I'm trying to loop through this to get the 'name' values. This is what I currently have, but it doesn't seem to be working, tried a few others from what was posted here but nothing seemed to work.

    $.get("/get_names", {campaign_id: $('select[name="id"]').val()}, 
                function(data){
                    $.each(data, function(i, item) {
                        alert(item);
                    });
                }
   );

Json being returned:

   [
           {
              "name":"age"
           },
           {
              "name":"asdf"
           },
           {
              "name":"drivername"
           },
           {
              "name":"drivers"
           },
           {
              "name":"firstname"
           },
           {
              "name":"gender"
           },
           {
              "name":"lastname"
           },
           {
              "name":"make"
           },
           {
              "name":"model"
           },
           {
              "name":"vehicles"
           },
           {
              "name":"year"
           }
        ]

I've tried using:

item.name
item[i].name

Any suggestions?

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to parse the string as JSON (data[0] == "[" is an indication that data is actually a string, not an object):

data = $.parseJSON(data);
$.each(data, function(i, item) {
    alert(item);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...