tags:

views:

57

answers:

3

I'm using the following code to get some json formatted data:

$.ajax({
            type: "GET",
            url: "MyService.svc/GetSomeData",
            dataType: "text",
            success: function (data, textStatus) {

                alert("Test: " + data.toString());
            },
            error: function (xhr, textStatus, errorThrown) {
                alert("Error: " + (errorThrown ? errorThrown : xhr.status));
            }
        });

Data is successfully returned to this call, and it looks like this:

{"d":"test data"}

My guess was that I could access the data as follows:

var myData = data["d"];

However this seems to always return "undefined". What am I missing to get the single string of data "test data"?

+2  A: 

what happens if you try data.d?

Thiago Santos
This is the correct answer.
antonlavey
Thanks, that did it!
James Cadd
+4  A: 

Change dataType: "text", to dataType: "json",

The problem you're having is that while the returned string is in fact valid JSON, it is being returned to your success function as a string. Strings don't have an attribute called d. What you need to do is convert the JSON to a javascript object -- which jQuery will do for you if you tell it that you're expecting JSON.

Sean Vieira
A: 

I think both Sean & Thiago are correct: use {dataType: "json"} (in your options to $.ajax()) and access the value with data.d.

Drew Wills
data["d"] will work just as fine as data.d. JavaScript object properties can be (and sometimes must be) referenced through array notation.
jmar777