jQuery ajax call failing with undefined error
My jQuery ajax call is failing with an undefined error. My js code looks like this:
$.ajax({
type: "POST",
url: "Data/RealTime.ashx",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 15000,
dataFilter: function(data, type) {
alert("RAW DATA: " + data + ", TYPE: "+ type);
return data;
},
error: function(xhr, textStatus, errorThrown) {
alert("FAIL: " + xhr + " " + textStatus + " " + errorThrown);
},
success: function(data) {
alert("SUCCESS");
}
});
My ajax source is a generic ASP.NET handler:
[WebService(Namespace = "http://my.website.com")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class RealTime : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.Write("{ data: [1,2,3] }");
context.Response.End();
}
public bool IsReusable
{ get { return false; } }
}
Now, if I return an empty object ("{ }"
) in my handler, the call will succeed. But when I return any other JSON object, the call fails.
The dataFilter
handler shows that I am receiving a correct object. Firebug shows the response as expected, and the JSON tab shows that the object is parsed correctly.
So what could be the cause?
[Edit] I should have actually written "when I return any invalid JSON object, 开发者_如何学编程the call fails"! :D
You need valid JSON! :)
Change this line:
context.Response.Write("{ data: [1,2,3] }");
To this:
context.Response.Write("{ \"data\": [1,2,3] }");
jQuery 1.4+ doesn't tolerate invalid JSON like it used to (fails silently/in weird ways), so just add the double quotes and you're all set. For a handy tool to test JSON validity, checkout JSONLint: http://www.jsonlint.com/
精彩评论