Jason94 Jason94 - 4 months ago 7
Ajax Question

How can I get json data thru ajax

I'm trying to create a chart page that updates every 5 seconds based on flotr2. But I'm having some problems with the return from the server, I get

[object, Object],[object, Object],[object, Object],[object, Object],[object, Object],[object, Object],[object, Object]


The javascript looks like:

function updateFunc() {

new Ajax.Request('http://localhost:53083/Home/Data', {
method: 'get',
onSuccess: function (transport) {
var json = transport.responseText.evalJSON();
alert(json);
}
});
}

updateFunc();


And the asp.net/c# looks like:

//
// GET: /Home/Data

public string Data()
{
dt.Rows.RemoveAt(0);

dt.Rows.Add(rand.Next(1, 50));

return JsonConvert.SerializeObject(dt);
}


dt is just a static datatable where i remove the first and add a new, creating a feel of continuous update.

What is wrong? As posted all i get is the
[object, Object]
from the alert.

Answer
  1. You need to change the response's media type to say it is JSON so the client will interpret it correctly:

    Response.ContentType = "application/json";
    

    (See here for the reference to the correct type.)

  2. It appears that JsonConvert doesn't know how to serialise the type of dt. Either change to a type that it can serialise, or tell it how to serialise that type: see the JSON.Net documentation.

Comments