Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do browsers want for the Content-Type header on json ajax responses?

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?

like image 395
Bruce Goodwin Avatar asked Jun 08 '10 23:06

Bruce Goodwin


1 Answers

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);
like image 58
zappan Avatar answered Nov 15 '22 14:11

zappan