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

Categories

I'm trying to use jQuery's each loop to go through this JSON and add it to a div named #contentHere. The JSON is as follows:

{ "justIn": [
  { "textId": "123", "text": "Hello", "textType": "Greeting" },
  { "textId": "514", "text":"What's up?", "textType": "Question" },
  { "textId": "122", "text":"Come over here", "textType": "Order" }
  ],
 "recent": [
  { "textId": "1255", "text": "Hello", "textType": "Greeting" },
  { "textId": "6564", "text":"What's up?", "textType": "Question" },
  { "textId": "0192", "text":"Come over here", "textType": "Order" }
  ],
 "old": [
  { "textId": "5213", "text": "Hello", "textType": "Greeting" },
  { "textId": "9758", "text":"What's up?", "textType": "Question" },
  { "textId": "7655", "text":"Come over here", "textType": "Order" }
 ]
}

I'm getting this JSON through use of this code:

$.get("data.php", function(data){

}) 

Any solutions?

See Question&Answers more detail:os

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

1 Answer

Try (untested):

$.getJSON("data.php", function(data){
    $.each(data.justIn, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.recent, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.old, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });    
});

I figured, three separate loops since you'll probably want to treat each dataset differently (justIn, recent, old). If not, you can do:

$.getJSON("data.php", function(data){
    $.each(data, function(k, v) {
        alert(k + ' ' + v);
        $.each(v, function(k1, v1) {
            alert(k1 + ' ' + v1);
        });
    });
}); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...