【发布时间】:2016-05-24 07:54:04
【问题描述】:
我正在尝试将 JSON 从表单发送到 spring mvc 控制器,但我总是收到错误 415。
我已经尝试过更改标题、类型、字符串化等,如其他帖子中所述,但没有成功。
有人可以帮忙吗?我是这方面的新手,仍在努力理解。
主页功能:
<script type="text/javascript">
function ConvertFormToJSON(form) {
var array = jQuery(form).serializeArray();
var json = {};
jQuery.each(array, function() {
json[this.name] = this.value || '';
});
return json;
}
jQuery(document).ready(function() {
jQuery('#novoitem').submit(function() {
var form = this;
var json = ConvertFormToJSON(form);
console.log(JSON.stringify(json));
jQuery.ajax({
dataType : "json",
contentType : "application/json",
type : "POST",
url : "inventario/",
data : JSON.stringify(json),
contentType : "application/json",
success : function(data) {
alert(data);
}
});
return false;
});
});
表格:
<form id="novoitem" method="post" enctype='application/json'>
<label for="usuario">Usuario:</label>
<input id="usuario" name="usuario" type="text">
<label for="tipo">Tipo:</label>
<input id="tipo" name="tipo" type="text">
<label for="nomeItem">Item:</label>
<input id="nomeItem" name="nomeItem" type="text">
<label for="quantidade">Quantidade:</label>
<input id="quantidade" name="quantidade"type="text">
<label for="vencimento">Vencimento:</label>
<input id="vencimento" name="vencimento" type="text">
<input type="submit" value="Incluir">
</form>
控制器:
@RequestMapping(value = "/inventario/", method = RequestMethod.POST)
public ResponseEntity<Void> insereItem(@RequestBody Item item){...}
Console.log 字符串化:
{"usuario":"a","tipo":"b","nomeItem":"c","quantidade":"d","vencimento":"e"}
错误:
POST http://localhost:8888/inventario/ 415 (Unsupported Media Type)
【问题讨论】:
-
replace : url : "inventario and @RequestMapping(value = "/inventario", method = RequestMethod.POST)
-
只需将所有 3 个 jackson jar 放在类路径上即可解决
标签: jquery json spring spring-mvc