【发布时间】:2017-04-07 17:05:12
【问题描述】:
我有这个 javascript 应该将 JSON 发送到我的 escreve POST REST 方法
$(document).ready(function() {
$("#idform").on('submit', function(e) {
e.preventDefault();
alert($("#idform").serialize());
$.ajax({
url : 'http://localhost:8080/DBRest/rest/escreve',
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#idform").serialize() // post data || get data
})
});
});
这是我的服务器端escreve 方法:
@POST
@Path("escreve")
@Consumes(MediaType.APPLICATION_JSON)
public void escreve(InputStream dado) throws IOException {
StringBuilder construtor = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(dado));
String linha = null;
while ((linha = in.readLine()) != null) {
construtor.append(linha);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(construtor.toString());
Pessoa pessoa = gson.fromJson(construtor.toString(), Pessoa.class);
Repo.escreve(pessoa);
}
不幸的是,我在 F12 的 Chrome 上收到了这条消息:
jquery.min.js:4 POST http://localhost:8080/DBRest/rest/escreve 415 (Unsupported Media Type)
send @ jquery.min.js:4
ajax @ jquery.min.js:4
(anonymous function) @ index.html:20
dispatch @ jquery.min.js:3
q.handle @ jquery.min.js:3
使用 js alert($("#idform").serialize()); 我得到了这个:nome=Mary&idade=12 这显然不是 JSON 解析的。我现在我的escreve 方法有效,因为我用一个正确发送 JSON 对象的 java 类对其进行了测试。
【问题讨论】:
-
所以你有一个接受 json 的方法,你发送的数据你知道 不是 json,你问为什么它不起作用?
-
@f1sh 我在问如何正确地做到这一点。显然,我不仅对最终答案感兴趣。我已经拿到了。如果您有任何其他知识,请提交答案。否则,只需投反对票并等待有人解释。
标签: javascript java jquery json ajax