8

I am returning some json which needs to be handled by javascript as the response to an XMLHTTPRequest.

If I set the response's content type to "text/plain", all browsers but Chrome will accept it and pass it to my JS with no problem. However, Chrome will wrap the response in

<pre style="word-wrap: break-word; white-space: pre-wrap;"> 

before passing it to my javascript.

If I set the response's content type to the "proper" "application/json" all browsers but Firefox will accept it and pass it to my JS with no problem. Firefox, however will ask to save or open the response as a file.

What's the correct, cross-browser Content-Type?

Bruce Goodwin
  • 308
  • 3
  • 8
  • possible duplicate of [The *right* JSON content type?](http://stackoverflow.com/questions/477816/the-right-json-content-type) – Ignacio Vazquez-Abrams Jun 08 '10 at 23:51
  • 1
    Maybe. Except that thread has the *wrong* answer (if you use the answer there, firefox behaves like a petulant child) – Bruce Goodwin Jun 09 '10 at 14:59
  • How does Firefox misbehave? If you're referring to saving and downloading, try the "Open in Browser" suggestion as referred to here: http://stackoverflow.com/questions/94767 – Matt DeKrey Jun 10 '10 at 14:23
  • Have observed this odd behaviour with Chrome. See http://stackoverflow.com/questions/18411670/tab-and-pre-wrapped-around-json-output-in-chrome – James P. Aug 23 '13 at 23:14

2 Answers2

9

You may solve the issue by parsing the response into the JSON object by using jQuery funcion parseJSON - http://api.jquery.com/jQuery.parseJSON/

The parameter you pass into the function is the JSON object string, which you extract from the response data:

function AjaxResponse (data) {  // AJAX post callback 
  var jsonResult = $.parseJSON(data.substring(data.indexOf("{"), data.lastIndexOf("}") + 1));
}

Tested (besides Chrome which problem this solves) in FF and IE8 for the following simple JSON result, for other browsers and more complex responses no guarantees...


NOTE: the content type in this case is text/plain or text/html I think - I've used the following ASP.Net MVC function to return the result

ContentResult System.Web.Mvc.Controller.Content(string content);

Where I returned the JSON object like

System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer 
    = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonResponse = jsonSerializer.Serialize(
    new { IArticleMediaId = 0
        , ImageUrl = Url.Content(fullImgPath)
        });
return Content(jsonResponse);
zappan
  • 3,668
  • 4
  • 29
  • 24
0

In ajaxFileUpload.js in uploadCallback() replace

io.contentWindow.document.body.innerHTML.innerHTML

with

$(io.contentWindow.document.body.innerHTML).html()
MrSalesi
  • 377
  • 3
  • 17