开发者

Why is my element giving me 'undefined' in this jquery .each() function...?

I'm开发者_如何学编程 having some problems with this jQuery....I'm new to it. It looks like it's the same as the example I'm taking it from...

$.getJSON('<%= Page.ResolveUrl("~/MyService.aspx") %>',
    function(data) {
        $.each(data, function(index, elem) {
            alert(elem.Name);
        });
    }
);

elem.Name always says 'undefined'! I'm getting the following data returned from my service...

{"ID":1,"Name":"David Bowie"}


You're getting mixed up in how .each works.

This by itself would work:

$.getJSON('<%= Page.ResolveUrl("~/MyService.aspx") %>',
    function(data) {
        alert(data.Name);
    }
);

data in your JSON callback is your JSON data.

The .each function will iterate through all the elements in that object and call your function once for each element. So your function would get called twice — once with index being ID and once with index being Name. That doesn't seem at all appropriate given the object you have.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜