什么是浏览器要对JSON Ajax响应的Content-Type头? [英] What do browsers want for the Content-Type header on json ajax responses?
问题描述
我返回一些JSON,需要通过JavaScript的处理为响应XMLHTT prequest。
I am returning some json which needs to be handled by javascript as the response to an XMLHTTPRequest.
如果我设置了响应的内容类型为text / plain的,所有的浏览器,但浏览器会接受它,它没有问题传递给我的JS。但是,Chrome将包裹在响应
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;">
在将它传递给我的javascript。
before passing it to my javascript.
如果我设置了响应的内容类型为正确的应用程序/ JSON所有的浏览器,但Firefox会接受它,它没有问题传递给我的JS。火狐,但会要求保存或打开响应为一个文件。
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?
推荐答案
您可以通过使用jQuery funcion parseJSON解析响应成JSON对象解决问题 - 的http://api.jquery.com/jQuery.parseJSON/
You may solve the issue by parsing the response into the JSON object by using jQuery funcion parseJSON - http://api.jquery.com/jQuery.parseJSON/
您传递到函数的参数是JSON对象的字符串,您从响应数据中提取:
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));
}
测试(除了浏览器这问题该解决了),在FF和IE8以下简单的JSON的结果,对于其他浏览器和更复杂的响应没有保证......
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...
注:在这种情况下,内容类型是text / plain或text / html的我想 - 我用下面的ASP.Net MVC函数返回的结果的
ContentResult System.Web.Mvc.Controller.Content(string content);
在哪里我回到像JSON对象的
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);
这篇关于什么是浏览器要对JSON Ajax响应的Content-Type头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!