ROB ENGG ROB ENGG - 3 months ago 10
Javascript Question

how to solve json data for loop

for (var key in data) {
$(".chat").html('<li class="\ left clearfix message \"></li>');
$(".message").html(data[key].message);
}


response data

[{"id":1,"message":"message 3","taker_id":"124","giver_id":"102","status":"0","stamp":"2016-08-24"},


{"id":5,"message":"message 2","taker_id":"124","giver_id":"102","status":"0","stamp":"2016-08-17"},{"id"
:6,"message":"This is the new message test service now we are ok","taker_id":"124","giver_id":"102","status"
:"0","stamp":"2016-08-11"}]

Output

<li class=" left clearfix message ">This is the new message test service now we are ok</li>


Problem :
html
  • not generated separately

    Please Help !

  • Answer

    With html() you are just replacing the content on every iteration. You need to append

    var resp = [{
      "id": 1,
      "message": "message 3",
      "taker_id": "124",
      "giver_id": "102",
      "status": "0",
      "stamp": "2016-08-24"
    }, {
      "id": 5,
      "message": "message 2",
      "taker_id": "124",
      "giver_id": "102",
      "status": "0",
      "stamp": "2016-08-17"
    }, {
      "id": 6,
      "message": "This is the new message test service now we are ok",
      "taker_id": "124",
      "giver_id": "102",
      "status": "0",
      "stamp": "2016-08-11"
    }]
    
    
    resp.forEach(function(obj) {
      $(".chat").append('<li class="left clearfix message ">' + obj.message + '</li>');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <ul class="chat"></ul>

    If you really do not want to have the text in the string, than you would need to do something like this:

    resp.forEach(function(obj) {
      var li = $('<li class="left clearfix message "></li>');
      li.text(obj.message);
      $(".chat").append(li);
    });