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

    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改