Monday, December 20, 2010

JSON, jQuery, IE, OData and a Parsererror

Quite a collection of technologies and approaches in that combination being used on a single page in SharePoint - mostly worked fine until I had deployed to a site using IE7. Suddenly my jQuery calls to $.getJSON() would silently fail, and with no error callback on the getJSON method, I resorted to an $.ajax call instead.

Experimenting in the error callback, found that even though the response status was success, there was an error - the error text was "parsererror". Seems that IE7's native parsing of JSON does behave too well for jQuery 1.4.2. Finally wrote some code in the error callback to detect when the err was parsererror, and in that instance to create a new JSON object using eval, similar to this:

$.ajax({
type: 'GET',
url: serviceUrl,
contentType: 'application/json: charset=utf-8',
dataType: "json",
success: ProcessResults,
error: function (xhr, textStatus, errThrown) {
if (textStatus == 'parsererror') {
var json;
try { json = eval('(' + xhr.responseText + ')'); }
catch (e) { }
ProcessResults(json);
}
}
});

After working out this fix, I found some information on stackoverflow suggesting that IE has problems with leading new line characters at the start of the JSON in the HTTP response body.

1 comment:

John Bonfardeci said...

Thank you for your post. This worked for me:

context.Response.ContentType = "application/json";
context.Response.ContentEncoding = UTF8Encoding.UTF8;

I found I could not simulate the problem running IE8 in IE7 mode. Only by installing IE7 on a virtual machine was I able to troubleshoot this for my IE7 clients.