weixin_33690367 2015-12-04 04:57 采纳率: 0%
浏览 28

通过循环进行JSON响应

I am using ajax to fetch a string from a PHP script. The string is in the format of a JSON array consisting of multiple objects.

I can successfully access the objects, but I have no luck when using a loop. I need to access the objects in reverse order.

AJAX STRING RESPONSE:

{
  "messages": [{
      "username": "John",
      "message": "Hello!",
      "age": 32,
    },
    {
      "username": "Bob",
      "message": "Awesome day",
      "age": 26,
    },
    {
      "username": "Sarah",
      "message": "How are you?",
      "age": 19,
    }
  ]
}

JAVASCRIPT:

var messageList = JSON.parse(ajax.responseText);

var message_count = messageList.messages.length;

while (message_count >= 0) {
    alert(messageList.messages[message_count].username);
    message_count -= 1;
}

I basically need the alerts to be in the order: Sarah Bob John I can access the array when I do something like: alert(messageList.messages[0].username);

It only seems to fail when I use the message_count variable. I have searched many hours for similar problems but found no success. Thank you in advance!

  • 写回答

2条回答 默认 最新

  • weixin_33743661 2015-12-04 05:03
    关注

    Your array has length 3, but arrays are indexed from zero, so you need to subtract 1 from your length total for the loop to work (messages[3] doesn't exist).

    var message_count = messageList.messages.length - 1;
    

    The loop will go from 2 to 0 and give you the correct output.

    DEMO

    评论

报告相同问题?