ajax - POST JSON 失败,出现 415 Unsupported media type,

我正在尝试向 servlet 发送 POST 请求。请求是通过 jQuery 以这种方式发送的:

var productCategory = new Object();
productCategory.idProductCategory = 1;
productCategory.description = "Descrizione2";
newCategory(productCategory);

newCategory 在哪里

function newCategory(productCategory)
{
  $.postJSON("ajax/newproductcategory", productCategory, function(
      idProductCategory)
  {
    console.debug("Inserted: " + idProductCategory);
  });
}

而 postJSON 是

$.postJSON = function(url, data, callback) {
    return jQuery.ajax({
    'type': 'POST',
    'url': url,
    'contentType': 'application/json',
    'data': JSON.stringify(data),
    'dataType': 'json',
    'success': callback
    });
};

使用 firebug 我看到 JSON 发送正确:

{"idProductCategory":1,"description":"Descrizione2"}

但我得到 415 Unsupported media type。 Spring mvc Controller 有签名

    @RequestMapping(value = "/ajax/newproductcategory", method = RequestMethod.POST)
public @ResponseBody
Integer newProductCategory(HttpServletRequest request,
        @RequestBody ProductCategory productCategory)

前几天有效,现在无效。如果需要,我会展示更多代码。

最佳答案

我之前使用 Spring @ResponseBody 发生过这种情况,这是因为没有随请求发送的接受 header 。使用 jQuery 设置 Accept header 可能会很痛苦,但这对我有用 source

$.postJSON = function(url, data, callback) {
    return jQuery.ajax({
    headers: { 
        'Accept': 'application/json',
        'Content-Type': 'application/json' 
    },
    'type': 'POST',
    'url': url,
    'data': JSON.stringify(data),
    'dataType': 'json',
    'success': callback
    });
};

@RequestBody 使用 Content-Type header 来确定请求中从客户端发送的数据的格式。 @ResponseBody 使用接受 header 来确定在响应中将数据发送回客户端的格式。这就是为什么你需要两个标题。

关于ajax - POST JSON 失败,出现 415 Unsupported media type, Spring 3 mvc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11492325/

相关文章:

c# - 如何将 C# 匿名类型序列化为 JSON 字符串?

json - 在 Unix shell 脚本中以可读的 JSON 格式显示 curl 输出

java - 在 Java 中将 XML 转换为 JSON 的最快方法

json - 在 Swift 中将字典转换为 JSON

json - 从 JSON 数据生成 JSON 模式的工具

python - 为什么我看到 "TypeError: string indices must be

javascript - 使用 Node.js 在 JSON 文件中写入/添加数据

jquery - 为什么每个人都为 jQuery 选择 JSON 而不是 XML?

javascript - 错误 "Uncaught SyntaxError: Unexpected

python - 如何将字典转储到 JSON 文件?