ROB ENGG ROB ENGG - 1 year ago 62
Javascript Question

how to solve json data for loop

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

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"


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

Problem :
  • not generated separately

    Please Help !

  • Answer Source

    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=""></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>');
    Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download