使用多维数组javascript处理web服务响应

Handling web service response with multidimensional array javascript

本文关键字:处理 web 服务 响应 javascript 数组      更新时间:2023-09-26

我正在消费一个具有多维数组响应的web服务,当我警告元素时,我得到未定义的输出,请参阅下面的代码。

JSON响应

{  
   "status":1,
   "msg":"cc call history",
   "records":{  
      "1":{  
         "destination":"Canada - Fixed Others",
         "date":"May 05, 2010",
         "time_spent":"1 minutes",
         "amount_charged":"2.18"
      },
      "2":{  
         "destination":"Canada - Fixed Others",
         "date":"May 05, 2010",
         "time_spent":"1 minutes",
         "amount_charged":"2.18"
      }
   }
}
Javascript代码

function call()
        {
            alert('call');
            var user_id = sessionStorage.getItem('user_id');
            var authentication_key = sessionStorage.getItem('auth_id');
            alert(user_id);
            alert(authentication_key);
            $.ajax({
                type: 'GET',
                url: 'http://example.com/XXX',
                data: {user_id: user_id, authentication_key: authentication_key},
                success: function (response)
                {
                    obj = JSON.parse(response);
                    var status = obj.status;
                    var msg = obj.msg;
                    var records;
                    alert(status);
                    alert(msg);
                    alert(records);
                    if (status === '0')
                    {
                        alert(status);
                    }
                    else
                    {
                        var lnrc = obj.records.length;
                        alert(lnrc);
                        for (var i = 0; i < 2; i++)
                        {
                            alert('for');
                            var rc1 = obj.records[i];
                            alert(rc1);
                        }
                    }
                },
                error: function () {
                },
            });
        }

请提出建议

可以使用for-in循环遍历object。确保你得到的键是object的实际property

var obj = {
  "status": 1,
  "msg": "cc call history",
  "records": {
    "1": {
      "destination": "Canada - Fixed Others",
      "date": "May 05, 2010",
      "time_spent": "1 minutes",
      "amount_charged": "2.18"
    },
    "2": {
      "destination": "Canada - Fixed Others",
      "date": "May 05, 2010",
      "time_spent": "1 minutes",
      "amount_charged": "2.18"
    }
  }
};
var status = obj.status;
var msg = obj.msg;
var records;
if (status === '0') {
  alert(status);
} else {
  for (var key in obj.records) {
    if (obj.records.hasOwnProperty(key)) {
      console.log(obj.records[key]);
    }
  }
  //OR
  Object.keys(obj.records).forEach(function(key) {
  console.log(obj.records[key]);
  });
}