Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 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 Reply

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...