简体   繁体   中英

Parse JSON object from Ajax response

I am using Ajax to retrieve a response from an external API.

This is my code:

<script type="text/javascript">
$("document").ready(function(){
  $(".nd-tracking").submit(function(){
    var data = {
      "action": "test"
    };
    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
      type: "POST",
      dataType: "json",
      url: "nd-request.php", 
      data: data,
      success: function(data) {
        $(".the-return").html(
          "<pre>" + data["json"] + "</pre>"
        );

        var obj = data["json"];
        for (var key in obj) {
          if (obj.hasOwnProperty(key)) {
            console.log(key + " -> " + obj[key]);
          }
        }
      }
    });
    return false;
  });
});
</script>
</head>
<body>
<form action="nd-request.php" method="post" class="nd-tracking">
    Consignment ID: <input type="text" value="" placeholder="Consignment ID" name="consignmentid"><br>
<input type="submit" name="submit" id="submit">
</form>

<div class="the-return">

</div>

My returned data is an object

[
{"code":{"0":"BKD"},"date":{"0":"2016-06-30"},"time":{"0":"08:51:33"},"trackEvent":{"0":"Magda Sliwa"}},
{"code":{"0":"ACC"},"date":{"0":"2016-06-30"},"time":{"0":"11:59:43"},"trackEvent":{"0":"Depot"},"carrierEvent":"accepted"},
{"code":{"0":"CRD"},"date":{"0":"2016-07-01"},"time":{"0":"09:56:00"},"carrierEvent":"Closed \/ carded"}
]

I've used this to format my Ajax request. Also, is it possible to return the JSON from the Ajax request and parse it via PHP?

How do I go through these and write them all out?

I think you are already getting the JSON encoded data , hence you can directly iterate through the response using the following code

...

success: function(data) {
    $.each(data, function(key,value) {
      alert(value.code[0] + '---' + value.date[0]); //and so on
    });
}

...

About Parsing via PHP

It seems you are already parsing the array in PHP an returning the JSON as response. If you have raw JSON data in PHP then you can convert it to an array using json_decode($data) and iterate through the array to do whatever you desire to do with the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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