2017-04-23 99 views
0

我有以下的jQuerySpring MVC和jQuery的产生415错误

<script> 
var response = ''; 
$.ajax({ type: "POST", 
    url: "http://localhost:8080/hsv06/checkUserExists", 
    async: false, 
    data: "title=foo", 
    success : function(text) 
    { 
     response = text; 
    } 
}); 

console.log(response); 
</script> 

这里是休息控制器:

@RequestMapping(value="/checkUserExists", method=RequestMethod.POST, consumes="application/json") 
public @ResponseBody boolean checkUser(@RequestBody Object title){ 
    System.out.println(title); 
    return true;   
} 

然而,这产生以下错误:

POST http://localhost:8080/hsv06/checkUserExists 415 (Unsupported Media Type) 
send @ jquery.min.js:2 
ajax @ jquery.min.js:2 
(anonymous) @ (index):57 

什么问题是什么?我发送数据的方式有什么问题?

回答

0

415表示不支持的媒体类型。你的服务器使用application/json,所以你的客户端必须提供application/json数据。要修复它,只需将类型添加到您的jQuery中,如下所示。

$.ajax({ type: "POST", 
    url: "http://localhost:8080/hsv06/checkUserExists", 
    async: false, 
    data: JSON.stringify({title: "food"}), 
    // specifying data type 
    contentType: "application/json; charset=utf-8", 
    success : function(text) 
    { 
     response = text; 
    } 
}); 

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')

When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8"

你的弹簧安置后端应该像下面这样。由于发布的数据是{title:“food”},Spring会将其解析为Map。

@RequestMapping(value="/checkUserExists", method=RequestMethod.POST, consumes="application/json") 
public @ResponseBody boolean checkUser(@RequestBody Map<String, String> param){ 
    System.out.println(param); 
    return true;   
} 
+0

仍然导致相同的错误 – user3809938

+0

好的,您的数据应该是json格式。但在你的代码中,它是data:“title = foo”,不是。你想要发布什么? –

+0

我已经更新了我的答案,请查看。基于你想发布字符串“title = foo”的假设。 –