我做錯了什麼?我嘗試使用Spring mvc和JSON。當我嘗試調試我的代碼時,我正在查看該JavaScript的作品,但不起作用的控制器。在瀏覽器中,我收到錯誤415 Unsupported Media Type。JSON加彈簧mvc 3.2錯誤415(不支持的介質類型)
腳本:
$(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」頭文件嗎?向我們展示你的'智能手機'類。 –