循环显示未定义,我无法看到我错误的地方

时间:2014-06-12 12:15:32

标签: javascript jquery json cordova

我正在通过jsonp循环来自.net网络服务的数据。类似的代码在其他地方有效,但我看不出我在哪里出错了。

通过以下方式检索数据:

if (pageId === 'alerts') {
        var Username = localStorage.getItem("Username");
        var SessionKey = localStorage.getItem("SessionID");
        console.log(Username);
        console.log(SessionKey);
        $.mobile.loading( 'show', { theme: "b", text: "Loading", textonly: false});
        $.ajax({
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            url: "http://redacted/GetData.asmx/GetLostAnimals",
            data: {Username: Username, SessionKey: SessionKey },
            dataType: "jsonp",
            success: myAlerts
        });
    }

var lostSelectedPet = 0;
function myAlerts(data)
{
    $("#alertsListMissingPets").empty();
    $.mobile.loading( 'hide', { theme: "b", text: "Loading", textonly: false});

    $.each(data, function(index) {
        console.log(data[index].LostDate)
        $("#alertsListMissingPets").append(" <li><a href=\"#\">"+ data[index].AnimalKey + " <span class=\"ui-li-count\">12</span></a></li>");
    });
    $("#alertsListMissingPets").listview('refresh');
}

$(document).on('click', '#alertsListMissingPets li a', function(){
    localStorage.setItem("lostSelectedPet", $(this).attr('data-custom'));
    editingId  = $(this).attr('data-custom');

});

返回的json就像:

callback(
 {
    AnimalKey: "f152e1c6baca181d9f3ca1f18c91cc41f23fc122545d9c8bff9f4cb2ea449874",
    LostDate: "11/06/2014 16:14:19",
    FoundDate: "",
    LostKey: "7560733274a7ca2ec43a85fcb9abd345fdc876acffac2b75ace7946035122fbd",
    Resp: "OK"
 }
)

然而,这会返回 - 它显示5个项目,但只有一个结果,上面的json是完整的响应。

enter image description here

1 个答案:

答案 0 :(得分:0)

您没有循环遍历数组,而是循环遍历对象。对象中有5个键,因此输出中有5行。

将响应更改为数组。

callback(
 [{  //<-- added [
    AnimalKey: "f152e1c6baca181d9f3ca1f18c91cc41f23fc122545d9c8bff9f4cb2ea449874",
    LostDate: "11/06/2014 16:14:19",
    FoundDate: "",
    LostKey: "7560733274a7ca2ec43a85fcb9abd345fdc876acffac2b75ace7946035122fbd",
    Resp: "OK"
 }]    //<-- added ]
)