json obj with array

时间:2014-10-23 09:41:37

标签: javascript json

如何使用javascript循环json对象内的联系人?

{
"success": 1,
"contacts": [
    {
        "cName": "testing",
        "cmail": "testMail",
        "ctlf": "testPhone"
    },
    {
        "cName": "testing",
        "cmail": "testMail",
        "ctlf": "testPhone"
    }
],
"fName": "Actura",
"fAdr": "langdyssen 5, 8200 Aarhus N",
"date": "14-9-2019"
}

我尝试使用下面的代码,但它只在控制台上显示0和1

$.getJSON("./ajax/get.php", {
        type: "printer",
        placement: "firm",
        id: id
    }).done(function (data) {
        if (data.success == 1) {
            //$('table#printerInfo').append("<tr><td>Printer ID</td><td>" + data.id + "</td></tr>").append("<tr><td>M&aeligrke</td><td>" + data.brand + "</td></tr>").append("<tr><td>Model</td><td>" + data.model + "</td></tr>").append("<tr><td>Farve</td><td>" + data.color + "</td></tr>");
            $('table td#firmName').append('<span class="glyphicon glyphicon-home"></span> ' + data.fName);
            $('table td#firmAdr').append('<span class="glyphicon glyphicon-globe"></span> ' + data.fAdr);
            $('table td#firmDate').append('<span class="glyphicon glyphicon-calendar"></span> ' + data.date);

            for (var contact in data.contacts) {
                console.log(contact);
            }
            console.log(data);
            toolTip();
        }
        else {
            alert("Der er sket en fejl: " + data.error);
        }
    });

将数据替换为测试数据,并且由于代码太多而无法使用。生病了,因为我因为答案而无法删除问题

1 个答案:

答案 0 :(得分:1)

请改用以下代码:

        for (var i in data.contacts) {
            console.log(data.contacts[i]);
        }