jQuery追加未定义

I'm having issues with appending a json. It print's multiple undefineds and i'm unsure what the cause is.

My code:

  $("button").click(function() {
    $.getJSON("https://api.myjson.com/bins/503aj", function(obj) {
      $.each(obj, function(key, test) {
        $("ul").append("<div>" + test.CustomerRef + "</div>" + "<div>" + obj.CustomerName + "</div>" + "<div>" + test.DelAddress1 + "</div>");
      });
    });
  });

Linked js fiddle showing the issue;

https://jsfiddle.net/7vshmzj7/

Why does it do it? and what are the possible workarounds?

The JSON you're getting back looks like this:

{
    "AddressData": {
        "OrderNo": "4200",
        "CustomerRef": "A1011",
        "DelAddress1": "4 Test Road",
        "DelAddress2": "Testing Lane",
        "DelAddress3": "Testland",
        "DelAddress4": "UK",
        "DelPostCode": "DB11 8DA"
    },
    "CustomerRef": "A1011",
    "CustomerName": "John Doe",
    "CustomerData": {
        "Email": "JohnDoe2500@gmail.com",
        "Phone": "07785442"
    }
}

That's not something you have to loop through with $.each, and looping through it with $.each is the problem.

Just use it directly:

$("button").click(function() {
    $.getJSON("https://api.myjson.com/bins/503aj", function(obj) {
        $("ul").append("<div>" + obj.CustomerRef + "</div>" + "<div>" + obj.CustomerName + "</div>" + "<div>" + obj.AddressData.DelAddress1 + "</div>");
    });
});

Note that the three fields you're accessing are accessed in that like this:

  • obj.CustomerRef
  • obj.CustomerName
  • obj.AddressData.DelAddress1

Updated Fiddle