我有這個JavaScript應該發送JSON我escreve
POST REST方法爲什麼我的POST方法不能接收這個Ajax?
$(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
方法工作,因爲我測試了一個java類正確地發送一個JSON對象。
所以,你必須接受JSON的方法,你發送的數據是* not * json,你問爲什麼它不起作用? – f1sh
http://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery – 1252748
@ f1sh我在問如何做到這一點。很明顯,我只對最終答案不感興趣。我已經知道了。如果您有任何其他知識,請提交答案。否則,請立即停止並等待某人解釋它。 – GabrielRado