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

若如初见. 提交于 2019-12-18 04:14:56

问题


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?


回答1:


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);



回答2:


In ajaxFileUpload.js in uploadCallback() replace

io.contentWindow.document.body.innerHTML.innerHTML

with

$(io.contentWindow.document.body.innerHTML).html()


来源:https://stackoverflow.com/questions/3002109/what-do-browsers-want-for-the-content-type-header-on-json-ajax-responses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!