JSON 内容类型有许多“标准 ” :

application/json
application/x-javascript
text/javascript
text/x-javascript
text/x-json

我用哪一种,在哪里?我假设安全和浏览器支持问题是一个因素。

相关:如果JSON被REST API送回,什么MIME类型?


当前回答

给杰森:

Content-Type: application/json

JSON -P: 给JSON -P:

Content-Type: application/javascript

其他回答

在 JSP 中,您可以在页面指令中使用此指令 :

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8"%>

JSON的正确MIME媒体类型是申请/json, JSP将用来向客户发送回复。

JSON的正确内容类型是应用程序/json UnLESS, 您正在使用JSONP, 也称为JSON with Padding, 实际上是 JavaScript, 所以正确的内容类型将是应用程序/javascript。

当然,对 JSON 来说正确的 MIME 媒体类型是应用程序/json, 但有必要了解在您的应用程序中需要什么样的数据。

例如,我使用Ext GWT, 服务器响应必须作为文本/ 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");
    }
});

如果使用应用程序/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);
    }
};

如果您在客户端环境中, 调查交叉浏览器支持是强制的, 对于一个支持良好的网络应用程序来说 。

右侧的 HTTP 内容- ype 将是应用程序/ json, 其他人也已经强调过, 但有些客户对它处理不当, 这就是为什么jQuery 推荐默认文本/ html 。

给杰森:

Content-Type: application/json

JSON -P: 给JSON -P:

Content-Type: application/javascript