我已经用JSON乱搞了一段时间,只是把它作为文本推送出去,它没有伤害任何人(据我所知),但我想开始正确地做事情。
我已经看到了**许多所谓的JSON内容类型的"标准"。
application/json
application/x-javascript
text/javascript
text/x-javascript
text/x-json
但哪一个才是正确的,或者说是最好的?我认为它们之间存在着安全和浏览器支持问题。
我知道有一个类似的问题,如果JSON被REST API返回,该用什么MIME类型?,但我想得到一个更有针对性的答案。
对于JSON文本。
application/json
JSON文本的MIME媒体类型是
application/json
。默认编码是UTF-8。(来源:RFC 4627)。)
对于JSONP(可运行的javascript)与回调。
application/javascript
以下是评论中提到的一些相关的博文。
text/html
。application/json
有问题 。当然,JSON的正确MIME媒体类型是application/json
,但有必要意识到在你的应用程序中期待什么类型的数据。
例如,我使用Ext GWT,服务器响应必须以text/html的形式进行,但包含JSON数据。
客户端,Ext GWT表单监听器。
uploadForm.getForm().addListener(new FormListenerAdapter()
{
@Override
public void onActionFailed(Form form, int httpStatus, String responseText)
{
MessageBox.alert("Error");
}
@Override
public void onActionComplete(Form form, int httpStatus, String responseText)
{
MessageBox.alert("Success");
}
});
在使用application/json响应类型的情况下,浏览器建议我保存该文件。
使用Spring MVC的服务器端源代码片段
return new AbstractUrlBasedView()
{
@SuppressWarnings("unchecked")
@Override
protected void renderMergedOutputModel(Map model, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
response.setContentType("text/html");
response.getWriter().write(json);
}
};