使用jQuery循环遍历JSON数组并输出数据

3
我目前正在开发一个功能来调用PHP文件获取一些XML数据,将其转换并返回为JSON数组数据。这个过程非常顺利,我已经成功获取和显示了这些数据,但是数组中有一部分需要循环遍历才能显示,我现在不知道如何处理。
以下是示例JSON数据:
{
   "TrackingRecord":{
      "Authorised":"Authorised(5.77.48.131)",
      "DeliveryAddress":{
         "CompanyName":"JAMES DERICK",
         "Address1":"6",
         "Address2":"LIBER HOUSE",
         "Address3":"OLYMPIAN",
         "Town":"YORK",
         "Postcode":"YO10 3UF",
         "ContactName":"JAMES DERICK",
         "ContactTelephone":"7507346318"
      },
      "CollectionAddress":{
         "CompanyName":"AMBIENT LOUNGE LTD",
         "Address1":"UNIT 3 LONG HEDGE LANE INDUSTR",
         "Address2":"BOTTESFORD",
         "Address3":{

         },
         "Town":"NOTTINGHAM",
         "Postcode":"NG13 0BF",
         "ContactName":"SARAH KIRBY",
         "ContactTelephone":"07879 442266074"
      },
      "ConsignmentInformation":{
         "Pieces":"1",
         "Pallets":"0",
         "Weight":"10",
         "Service":"Priority 1",
         "DeliveryDate":"2016-02-29T00:00:00",
         "ItemsDelivered":"1",
         "ConsignmentRef":"2838",
         "SpecialInstructions":"JAMES DERICK 7507346318 {JAMES\u003Cbr\u003E14075@GMAIL.COM}\u003Cbr\u003E",
         "AdditionalReferencesInformation":{
            "AdditionalReferences":{
               "Reference":"2838"
            }
         }
      },
      "MovementInformation":{
         "Movement":[
            {
               "MovementDate":"2016-02-25T00:00:00",
               "MovementTime":"0001-01-01T10:00:04",
               "Description":"Created By EZEEWEB",
               "DeliveryDepot":"Leeds",
               "Round":"019",
               "DeliveryDate":"2016-02-26T00:00:00",
               "PackagesReceived":"0",
               "PackagesDelivered":"0"
            },
            {
               "MovementDate":"2016-02-26T00:00:00",
               "MovementTime":"0001-01-01T07:11:53",
               "Description":"Out to deliver",
               "DeliveryDepot":"Leeds",
               "Round":"019",
               "DeliveryDate":"2016-02-26T00:00:00",
               "PackagesReceived":"1",
               "PackagesDelivered":"0"
            },
            {
               "MovementDate":"2016-02-26T00:00:00",
               "MovementTime":"0001-01-01T11:00:53",
               "Description":"Failed - Other reason",
               "DeliveryDepot":"Leeds",
               "Round":"019",
               "DeliveryDate":"2016-02-29T00:00:00",
               "PackagesReceived":"1",
               "PackagesDelivered":"0"
            },
            {
               "MovementDate":"2016-02-27T00:00:00",
               "MovementTime":"0001-01-01T05:59:32",
               "Description":"Out to deliver",
               "DeliveryDepot":"Leeds",
               "Round":"019",
               "DeliveryDate":"2016-02-29T00:00:00",
               "PackagesReceived":"1",
               "PackagesDelivered":"0"
            },
            {
               "MovementDate":"2016-02-29T00:00:00",
               "MovementTime":"0001-01-01T10:55:43",
               "Description":"Delivered",
               "DeliveryDepot":"Leeds",
               "Round":"019",
               "DeliveryDate":"2016-02-29T00:00:00",
               "PackagesReceived":"1",
               "PackagesDelivered":"1"
            }
         ]
      },
      "TimedInformation":{
         "TimedDelivery":{
            "Signature":"DERICK",
            "SignatureDate":"2016-02-29T00:00:00",
            "SignatureTime":"0001-01-01T10:55:00"
         }
      },
      "ScanInformation":{
         "Scan":[
            {
               "PieceID":"148426702251072001",
               "Description":"Auto Inbound Scan   ()",
               "Depot":"Newark",
               "ScanDate":"2016-02-25T00:00:00",
               "ScanTime":"0001-01-01T17:12:01",
               "ScannedBy":"NWK CONVYR"
            },
            {
               "PieceID":"148426702251072001",
               "Description":"Auto Inbound Scan   ()",
               "Depot":"Leeds",
               "ScanDate":"2016-02-26T00:00:00",
               "ScanTime":"0001-01-01T02:22:08",
               "ScannedBy":"LDS CONVYR"
            },
            {
               "PieceID":"148426702251072001",
               "Description":"Load C & D          (019)",
               "Depot":"Leeds",
               "ScanDate":"2016-02-26T00:00:00",
               "ScanTime":"0001-01-01T03:37:45",
               "ScannedBy":"CJONES"
            },
            {
               "PieceID":"148426702251072001",
               "Description":"Load C & D          (019)",
               "Depot":"Leeds",
               "ScanDate":"2016-02-26T00:00:00",
               "ScanTime":"0001-01-01T23:43:22",
               "ScannedBy":"CJONES"
            }
         ]
      },
      "ImageInformation":{
         "PODImage":{
            "URL":"http:\/\/www.tpeweb.co.uk\/ezpod\/tpenas\/valid\/20160229\/014842672838___________00000_01.tif"
         }
      }
   }
}

JS代码段:

<div id="tracking">
      <div class="delivery"></div>
      <div class="movement"></div>
    </div>
    <script type="text/javascript">
    $("document").ready(function(){
       var account = getUrlParameter('account');
       var reference = getUrlParameter('reference'); 
       $.ajax({
         url: 'http://www.ambientlounge.com/external/ukTracking.php',
         type: 'POST', 
         dataType: "json",
         data: {
           account: account,
           reference: reference
         }, 
         success: function(json){
           $('#tracking .delivery').html(
             "<h3>Delivery Details</h3><p>Name: " + json["TrackingRecord"]["DeliveryAddress"]["CompanyName"] + "<br /><h5>Address:</h5>" + json["TrackingRecord"]["DeliveryAddress"]["Address1"] + "<br />" + json["TrackingRecord"]["DeliveryAddress"]["Address2"] + "<br />" + json["TrackingRecord"]["DeliveryAddress"]["Address3"] + "<br />" + json["TrackingRecord"]["DeliveryAddress"]["Town"] + "<br />" + json["TrackingRecord"]["DeliveryAddress"]["Postcode"] + "</p>"
           );
           for (var i = 0; i < json["MovementInformation"]["Movement"].length; i++) {
             console.log(json); // stuck here if im doing right at all!
           }
         }
       });
    });

    var getUrlParameter = function getUrlParameter(sParam) {
      var sPageURL = decodeURIComponent(window.location.search.substring(1)),
          sURLVariables = sPageURL.split('&'),
          sParameterName,
          i;

      for (i = 0; i < sURLVariables.length; i++) {
          sParameterName = sURLVariables[i].split('=');

          if (sParameterName[0] === sParam) {
              return sParameterName[1] === undefined ? true : sParameterName[1];
          }
      }
    };

    </script>

目前我只获取了“DeliveryAddress”数据,这很好用,因为没有要遍历的内容,但现在我有多个点在数组“MovementInformation”>“Movement”中,其中有多个部分需要遍历和显示,但不知道如何做到这一点。


尝试使用以下代码:for (var i = 0; i < json.MovementInformation.Movement.length; i++) {console.log(json.MovementInformation.Movement[i]);} - Alex Tartan
@James,我很好奇,为什么你要将 xml 转换为 json,即使你可以使用 jquery 解析 xml - HddnTHA
我可能走了一个冗长的路线...这是为了将数据拉入Shopify,但我认为当我尝试时,我遇到了Access-Control-Allow-Origin错误,到目前为止,我只发现最好的方法是在我的服务器上创建一个PHP文件,并为该域添加Access-Control-Allow-Origin,然后使用file_get_contents并传回到Shopify模板上的jQuery以获取数据。 - James
顺便提一下,当您允许新域名进行访问控制时,ajax也可以使用xml。另外祝您解决问题顺利。 - HddnTHA
有没有办法在不在 PHP 文件中设置允许的域名的情况下避免使用 file get contents 从其他域名发出的 AJAX 请求时出现访问控制问题? - James
1个回答

1
json.TrackingRecord.MovementInformation.Movement.forEach(function(item) {
  console.log(item)
})

我复制并粘贴了你的JSON数据,然后使用foreach来获取每个项目并处理,很奇怪。 - Sarantis Tofas
请确保您已经打开了控制台。 - Sarantis Tofas
理想情况下,希望避免使用任何插件,因为这是一个Shopify模板,需要减少负载,但会进行检查,新的日期是否有用? - James
啊,谢谢伙计,是的,我想可以工作...可否添加年份?要么2016年或16年?我刚刚添加了MovementTime,有没有办法格式化它?再次感谢您的所有帮助!保证这将是最后一点;)https://jsfiddle.net/3kfzfvd0/1/ - James
让我们在聊天中继续这个讨论 - Sarantis Tofas
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接