简体   繁体   English

通过循环进行JSON响应

[英]JSON response through loop

I am using ajax to fetch a string from a PHP script. 我正在使用ajax从PHP脚本中获取字符串。 The string is in the format of a JSON array consisting of multiple objects. 该字符串采用由多个对象组成的JSON数组的格式。

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: AJAX字符串响应:

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

JAVASCRIPT: 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); 我基本上需要按顺序排列警报:Sarah Bob John我可以执行以下操作来访问数组:alert(messageList.messages [0] .username);

It only seems to fail when I use the message_count variable. 当我使用message_count变量时,它似乎只失败了。 I have searched many hours for similar problems but found no success. 我已经搜索了许多小时以寻找类似的问题,但是没有成功。 Thank you in advance! 先感谢您!

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). 您的数组的长度为3,但是数组从零开始索引,因此您需要从总长度中减去1才能使循环生效( messages[3]不存在)。

var message_count = messageList.messages.length - 1;

The loop will go from 2 to 0 and give you the correct output. 循环将从2变为0,并为您提供正确的输出。

DEMO DEMO

try this: 尝试这个:

$.getJSON( url, function( data ) {
    var messages = data.messages || {};
    $.each(messages,function(key,info){
        console.log(info.username);
        console.log(info.message);
        console.log(info.age);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM