tags:

views:

28

answers:

2

Hi

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"}
+4  A: 

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.

VoteyDisciple
Thanks, mate...I just realised my service was returning 1 object whilst the service in the example I was following was returning an array of objects.
Sambo
A: 

above answer is best :)

Orbit