【发布时间】:2014-02-16 03:16:43
【问题描述】:
我做错了什么?我尝试使用 Spring mvc 和 JSON。当我尝试调试我的代码时,我正在寻找 javascript 工作但不能工作的控制器。在浏览器中,我收到错误 415 Unsupported Media Type。
脚本:
$(document).ready(function() {
$('#newSmartphoneForm').submit(function(event) {
var producer = $('#producer').val();
var model = $('#model').val();
var price = $('#price').val();
var json = { "producer" : producer, "model" : model, "price": price};
$.ajax({
url: $("#newSmartphoneForm").attr( "action"),
data: JSON.stringify(json),
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(smartphone) {
var respContent = "";
respContent += "<span class='success'>Smartphone was created: [";
respContent += smartphone.producer + " : ";
respContent += smartphone.model + " : " ;
respContent += smartphone.price + "]</span>";
$("#sPhoneFromResponse").html(respContent);
}
});
event.preventDefault();
});
});
控制器:
@RequestMapping(value="/create", method=RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Smartphone createSmartphone(@RequestBody Smartphone smartphone) {
return smartphoneService.create(smartphone);
}
【问题讨论】:
-
您使用的是哪个 Spring MVC 版本?打开您的网络控制台。您是否看到正在发送的
Content-Type标头?向我们展示您的Smartphone课程。
标签: java javascript ajax spring-mvc