从Ajax响应中提取

时间:2012-01-17 22:54:34

标签: javascript ajax json

我有一个返回JSON数据(Data Attached)的ajax调用。 将数据转换为String后,它的外观如下:

{
   "shipments":[
      {
         "companyName":"TriStar Inc.",
         "shipmentDate":null,
         "transMode":"NDAY",
         "paid":true,
         "delDate":null,
         "custRefInfo":{
            "customerName":"DAISY N.",
            "customerZip":"90544"
         },
         "orderStatus":true
      },
      {
         "companyName":"Carbo Box",
         "shipmentDate":null,
         "transMode":"COUR",
         "paid":true,
         "delDate":null,
         "custRefInfo":{
            "customerName":"TOM K",
            "customerZip":"07410"
         },
         "orderStatus":true
      }
   ]
}

现在,当我在Firefox中打印JSON响应时,它看起来像:

[Object { companyName="TriStar Inc.", shipmentDate=null, transMode="NDAY", more...}, Object { companyName="Carbo Box", shipmentDate=null, transMode="COUR", more... } ]

我的问题是,如何从此响应中提取companyName和customerName字段。以下不起作用:

 load: function(response){
        for(var i in response){
             console.log(response.shipments[i].companyName);
  }

2 个答案:

答案 0 :(得分:2)

如果你得到一个json的字符串,你需要先解析它。

var obj = JSON.parse(jsonString);

现在你有一个正确的对象文字,你可以正常访问它

var shipments = obj.shipments;

shipments现在是一个javascript数组...

for(var i = 0; i < shipments.length; i++){
    console.log(shipments[i].companyName);
}

请注意,不应在数组上使用for(var i in x)构造。

答案 1 :(得分:0)

response.shipments[i].companyName